Let's say I have these schemes:
defmodule Sample.Post do use Ecto.Schema schema "post" do field :title has_many :comments, Sample.Comment end end defmodule Sample.User do use Ecto.Schema schema "user" do field :name has_many :comments, Sample.Comment end end defmodule Sample.Comment do use Ecto.Schema schema "comment" do field :text belongs_to :post, Sample.Post belongs_to :user, Sample.User end end
My questions are: how can I use Ecto.build_assoc to save a comment?
iex> post = Repo.get(Post, 13) %Post{id: 13, title: "Foo"} iex> comment = Ecto.build_assoc(post, :comments) %Comment{id: nil, post_id: 13, user_id: nil}
So far so good, all I have to do is use the same function to set user_id in my Comment structure, but since the return value of build_assoc is Comment struct, I cannot use the same function
iex> user = Repo.get(User, 1) %User{id: 1, name: "Bar"} iex> Ecto.build_assoc(user, :comment, comment) ** (UndefinedFunctionError) undefined function: Sample.Comment.delete/2 ...
I have two options, but none of them look good:
First you need to set user_id manually!
iex> comment = %{comment| user_id: user.id} %Comment{id: nil, post_id: 13, user_id: 1}
The second is to convert the structure into a map and ... I donβt even want to go there
Any suggestion?
elixir ecto associations
slashmili
source share