Ecto: Add function to build models from multiple associated models

Created on 21 Sep 2015  路  9Comments  路  Source: elixir-ecto/ecto

Ecto.Model.build/3 can only create a model from one association. To create models from multiple associations today you have to manually set some foreign key fields.

Intermediate

Most helpful comment

Hi @aesmail! This issue is literally three years old. It is probably better to request feedback on ElixirForum or similar platform where more people can join the discussion and share their experiences. :)

All 9 comments

Closing this, low priority for now.

@josevalim @ericmj Is there a workaround for this in the mean time?

You can always set the foreign keys manually

Just set the ids directly: %Comment{user_id: user.id, post_id: post.id}

Okay, so the issue was not with the association, but with the required fields in the changeset. How do you then make the association a required field without making the changeset invalid by setting the ids directly?

@expelledboy

If you are using cast_assoc with the required option, you'd have to preload the association before casting the struct into a changeset

Tackling this old issue and trying to find out the best "current" solution.

I have Receipt with many Items. Both of them have a foreign key to Account.
I'm using cast_assoc(:items, with: &Item.new_changeset/2) in Receipt to save both the receipt and the items in one shot. What's the best way to include account_id in Item?

Adding it manually would require getting the "items" field out of the params (if it exists) and adding an account_id field with the desired value and replacing the old "items" list with the new one.

Any better way to do it?

Hi @aesmail! This issue is literally three years old. It is probably better to request feedback on ElixirForum or similar platform where more people can join the discussion and share their experiences. :)

Will do @josevalim thanks for the suggestion and quick response. And thank you for such a joyful and artistic piece of software that is Ecto 馃憤馃徏.

Was this page helpful?
0 / 5 - 0 ratings