gpt4 book ai didi

associations - Ecto 与多个计划的关联

转载 作者:行者123 更新时间:2023-12-04 10:36:07 25 4
gpt4 key购买 nike

假设我有这些模式:

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

我的问题是如何使用 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}

到目前为止一切正常,我需要做的就是使用相同的函数来设置 user_id在我的 Comment struct,但是因为返回值 build_assocComment struct,我不能使用相同的功能
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
...

我有两个选择,但对我来说它们都不好看:

第一个是设置 user_id手动!
iex> comment = %{comment| user_id: user.id}
%Comment{id: nil, post_id: 13, user_id: 1}

第二个是将结构转换为映射......我什至不想去那里

有什么建议吗?

最佳答案

为什么不想将结构转换为映射?这真的很容易。
build_assoc期望属性映射作为最后一个值。它在内部尝试删除 key :__meta__ .结构具有编译时保证,它们将包含所有定义的字段,因此您将获得:

** (UndefinedFunctionError) undefined function: Sample.Comment.delete/2

但你可以写:
comment = Ecto.build_assoc(user, :comment, Map.from_struct comment)

一切都会好起来的。

关于associations - Ecto 与多个计划的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com