Phoenix 没有 belongs_to 的 Ecto has_one
Ecto has_one without belongs_to in Phoenix
我有一个 Home
模型,其中包含主页内容,例如 intro_copy
、about_image
和 about_copy
。
在 Home
模型上,我还希望能够使用 has_one
关系突出我的 Post
模型中的 3 个帖子。基本上只是使用 id 链接它们。
我的 Home
架构如下所示:
schema "home" do
field :intro_copy, :string
field :about_copy, :string
field :about_image, Image.Type
has_one :post_1, Post
has_one :post_2, Post
has_one :post_3, Post
timestamps()
end
我的 changeset
函数如下所示:
def changeset(struct, params \ %{}) do
struct
|> cast_assoc(params, [:post_1, :post_2, :post_3])
|> cast(params, @required_fields, @optional_fields)
end
此外,在我的迁移中,我将以下行添加到 :home
table:
add :post_1_id, references(:posts)
add :post_2_id, references(:posts)
add :post_3_id, references(:posts)
这里有什么地方我明显出错了吗?
如果 home
table 包含对 posts
的引用,那么 Home
应该 belongs_to
Post
。 has_one
是相反的——如果 posts
包含引用 home
.
的字段,您将在此处使用它
如果你改变:
has_one :post_1, Post
has_one :post_2, Post
has_one :post_3, Post
至
belongs_to :post_1, Post
belongs_to :post_2, Post
belongs_to :post_3, Post
一切都应该适用于您已经编写的迁移。
我有一个 Home
模型,其中包含主页内容,例如 intro_copy
、about_image
和 about_copy
。
在 Home
模型上,我还希望能够使用 has_one
关系突出我的 Post
模型中的 3 个帖子。基本上只是使用 id 链接它们。
我的 Home
架构如下所示:
schema "home" do
field :intro_copy, :string
field :about_copy, :string
field :about_image, Image.Type
has_one :post_1, Post
has_one :post_2, Post
has_one :post_3, Post
timestamps()
end
我的 changeset
函数如下所示:
def changeset(struct, params \ %{}) do
struct
|> cast_assoc(params, [:post_1, :post_2, :post_3])
|> cast(params, @required_fields, @optional_fields)
end
此外,在我的迁移中,我将以下行添加到 :home
table:
add :post_1_id, references(:posts)
add :post_2_id, references(:posts)
add :post_3_id, references(:posts)
这里有什么地方我明显出错了吗?
如果 home
table 包含对 posts
的引用,那么 Home
应该 belongs_to
Post
。 has_one
是相反的——如果 posts
包含引用 home
.
如果你改变:
has_one :post_1, Post
has_one :post_2, Post
has_one :post_3, Post
至
belongs_to :post_1, Post
belongs_to :post_2, Post
belongs_to :post_3, Post
一切都应该适用于您已经编写的迁移。