Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto has_one without belongs_to in Phoenix

I have a Home model which contains content for a home page such as intro_copy, about_image and about_copy.

On the Home model, I’d also like to be able to feature 3 posts from my Post model using has_one relationship. Basically just linking them using an id.

My Home schema looks like this:

schema "home" do
  field :intro_copy, :string
  field :about_copy, :string
  field :about_image, Image.Type

  has_one :post_1, Post
  has_one :post_2, Post
  has_one :post_3, Post

  timestamps()
end

My changeset function looks like this:

def changeset(struct, params \\ %{}) do
  struct
  |> cast_assoc(params, [:post_1, :post_2, :post_3])
  |> cast(params, @required_fields, @optional_fields)
end

Also, in my migrations I have the following lines being added to the :home table:

add :post_1_id, references(:posts)
add :post_2_id, references(:posts)
add :post_3_id, references(:posts)

Is there somewhere I’m obviously going wrong here?

like image 763
gosseti Avatar asked Mar 01 '17 18:03

gosseti


1 Answers

If the home table contains references to posts, then Home should belongs_to Post. has_one is for the reverse -- you'd use it here if posts contained a field that referenced home.

If you change:

has_one :post_1, Post
has_one :post_2, Post
has_one :post_3, Post

to

belongs_to :post_1, Post
belongs_to :post_2, Post
belongs_to :post_3, Post

everything should work with the migration you've already written.

like image 101
Dogbert Avatar answered Oct 14 '22 13:10

Dogbert