假设我有这些模式:
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
Run Code Online (Sandbox Code Playgroud)
我的问题是如何Ecto.build_assoc用来保存评论?
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}
Run Code Online (Sandbox Code Playgroud)
到目前为止还可以,我需要做的就是使用相同的函数来设置user_id我的Comment结构,但是由于返回值build_assoc是Comment …