Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto build multiple assoc

Currently working on Phoenix project using Ecto + Postgres. When creating a comment, as comment belongs_to both User and Article, is there a way to build multiple associations to generate one changeset?

Something like this pseudocode

comment_changeset = build_assoc(article, :comment) 
                 |> build_assoc(user, :comment)

Any ideas?

like image 817
Albert Nemec Avatar asked Mar 13 '17 01:03

Albert Nemec


1 Answers

As Justin mentioned, you can use put_assoc to do that, so off the top of my head I think something like this should work.

comment_changeset =
  article
  |> Ecto.build_assoc(:comment)
  |> Ecto.Changeset.change()
  |> Ecto.Changeset.put_assoc(:user, user)
like image 54
NoDisplayName Avatar answered Oct 25 '22 22:10

NoDisplayName