elixir - Ecto association to more than one schemes -


let's have these schemas:

defmodule sample.post   use ecto.schema    schema "post"     field :title     has_many :comments, sample.comment   end end  defmodule sample.user   use ecto.schema    schema "user"     field :name     has_many :comments, sample.comment   end end  defmodule sample.comment   use ecto.schema    schema "comment"     field :text     belongs_to :post, sample.post     belongs_to :user, sample.user   end end 

my questions how can use ecto.build_assoc save 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 it's ok, need use same function set user_id in comment struct, since return value of build_assoc comment struct, can not use 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 2 options neither of them looks me:

first 1 set user_id manually!

iex> comment = %{comment| user_id: user.id} %comment{id: nil, post_id: 13, user_id: 1} 

second 1 convert struct map , ... don't want go there

any suggestion?

why don't want convert struct map? easy.

build_assoc expects map of attributes last value. internally tries delete key :__meta__. structs have compile time guarantees, contain defined fields, getting:

** (undefinedfunctionerror) undefined function: sample.comment.delete/2 

but can write:

comment = ecto.build_assoc(user, :comment, map.from_struct comment) 

and work fine.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -