Search code examples
ruby-on-railselixirphoenix-frameworkecto

How to insert a parent model and a few child ones at once in Phoenix/Elixir?


I have the Article and Commentary models. I want to insert and Article and a few Commentary at once. How can I do that? In the documentation it's not shown. In Rails I'd do that something like this:

article = Article.create!(title: "title1", body: "body1")
article.commentaries = [
    Commentary.create!(body: "comment body1"),
    Commentary.create!(body: "comment body2"),
    Commentary.create!(body: "comment body3")
]
article.save!

How about Phoenix/Elixir?


Solution

  • %Article{}
    |> Ecto.Changeset.change(title: "title1")
    |> Ecto.Changeset.put_assoc(comments: [%Comment{body: "one"}, %Comment{body: "two"}])
    |> Repo.insert!()
    

    I believe it's something like this, you'll figure it out from here.