【发布时间】:2015-08-25 13:21:26
【问题描述】:
我正在使用 Elixir 和 Phoenix Web 框架,但现在我一直在尝试验证外键约束。所以,给定一个模型Post 和许多cmets,我写了Comment 模型如下:
defmodule MyApp.Comment do
use MyAPp.Web, :model
schema "comments" do
field :body, :text
belongs_to :post, MyApp.Post
timestamps
end
@required_fields ~w(body post_id)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> foreign_key_constraint(:post_id)
end
end
及其单元测试:
defmodule MyApp.CommentTest do
# [...]
test "changeset with non existent post" do
attrs = %{
body: "A comment."
post_id: -1 # some non-existent id?
}
refute Comment.changeset(%Comment{}, attrs).valid?
assert {:post_id, "does not exist"} in errors_on(%Comment{}, %{})
end
end
根据http://hexdocs.pm/ecto/Ecto.Changeset.html#foreign_key_constraint/3:
外键约束依靠数据库来检查 关联模型是否存在。这有助于保证 仅当父项存在于数据库中时才会创建子项 也是。
我希望我编写的代码能够正常工作,但它只检查存在(如@required_fields ~w(body post_id) 中所定义)。我不排除我做错了什么或误解了文档中的声明。
有没有人偶然发现过这个?
更新: 为了完整起见,这里是迁移:
def change do
create table(:comments) do
add :body, :text
add :post_id, references(:posts)
timestamps
end
create index(:comments, [:post_id])
end
【问题讨论】:
-
能否请您也提供您的迁移?
-
@Gazler 编辑了我的问题,添加了迁移。
标签: elixir phoenix-framework ecto