I'm getting rather confused about Ecto when it comes to adding a new association to an existing model. Let's say I have some discussion board where users can like a post, and I have the following models:
schema "discussion_items" do
many_to_many :likes, XXX.Tag, join_through: "discussion_items_likes"
timestamps()
end
schema "likes" do
belongs_to :user, XXX.User
timestamps()
end
Now lets say I have an existing DiscussionItem and I want to add a like association to this, here's what Im trying (simplified):
user = Repo.one(User)
discussion_item = Repo.one(from d in DiscussionItem, preload [:likes])
like_changeset = Like.changeset(%Like{})
|> Ecto.Changeset.put_assoc(:user, user)
changeset = Ecto.Changeset.change(discussion_item)
|> Ecto.Changeset.put_assoc(:likes, [like_changeset])
Ecto.update!(changeset)
What I am finding is that this will create the Like and the association correctly the first time but then complain afterwards that I need additional information in the form of some id:
you are attempting to change relation :likes of XXX.DiscussionItem, but there is missing data
If you are attempting to update an existing entry, please make sure you include the entry primary key (ID) alongside the data.
If you have a relationship with many children, at least the same N children must be given on update. By default it is not possible to orphan embed nor associated records, attempting to do so results in this error message.
So here's the things that confuse me (there are a few):
- This error message seems to suggest that in order to update one associated item, I need to provide a change set with ALL items including the one that changed. This seems nuts, so I'm guessing I'm reading this wrong.
- I don't want to update the likes association -- I want to add one. Is put_assoc the wrong choice here?
- Do I really need to preload the likes just to insert an item? Even on update I don't want to load the whole collection of associations to change one.
- Do I need to load
UserandDicussion_itemto add a like here?
many_to_manyfor likes and discussion items? Shouldn't a like count for only a single discussion item at a time? - Justin Wood