Now the question is quite simple, in Ruby’s ActiveRecord, there’s a convenient setter where you can just set to an array of IDs of the associated records, and it will automatically update the join records, ie.: product.tag_ids = [1, 2, 5, 6]
In Ecto if I want to use put_assoc, it requires me to preload all the tags in a array, so I can perform put_assoc(:tags, tags)?
What if I don’t want to preload them, like it’s done in ActiveRecord?
Maybe you can insert your data directly into the join table? Might not be the best approach, but it would work (if there are no conflicts; if there are, then :on_conflictoption might be helpful).
Hey @aseigo, thanks for your answer. But if you look in the guide, he’s basically getting all the existing tags from the database and creating the tags which do not exist.
In my case I just receive an array of ids of tags, I don’t want to load them, just create the intermediate join…
So I think something like @idi527 wrote is maybe the way to go. But because I’m receiving a final array everytime I will have to remove first all the existing join records, before inserting all them again… so I will have to use a transaction or a Multi…
I thought first that this kind of use case was common and would be integrated in Ecto, it’s been there for a while in Ruby’s ActiveRecord and Mongoid…
If I understand correctly, put_assoc only make sure parent is associated with the record.
So why can’t I fool it by doing this?
put_assoc(:tags, [%Tag{id: 1}, %Tag{id: 3}]) or more elegantly…
put_assoc(:tags, Enum.map(tag_ids, fn x -> %Tag{id: x} end))
Its all ecto need to know to update association right?