How to add 4 relations at time

Hi

i have 4 schemas

main schema -> has many contacts, address, emails
contact -> belongs to main schema
address -> belongs to main schema
emails -> belongs to main schema

this code is working fine for inserting one relation

post = Ecto.Changeset.change(%Post{}, title: "Hello", body: "world")
comment = Ecto.Changeset.change(%Comment{}, body: "Excellent!")
post_with_comments = Ecto.Changeset.put_assoc(post, :comments, [comment])
Repo.insert!(post_with_comments)

dont understand how i can add all 3 relation with main schema at once.
please help

If You want to create all at once, it is probably better to use cast_assoc instead of put_assoc.

From the link…

cast_assoc/3 is used when you want to create the associated record along with your changeset. This might be what you are looking for if you are coming from Rails and looking for ‘accepts_nested_attributes_for’

1 Like