【发布时间】:2016-08-30 02:24:00
【问题描述】:
我有 2 个模型,User 和 Role。 Userhas_manyRoles。我也设置了外键约束(如果有任何用户拥有这个角色,你不能删除角色)。
我在尝试实施时遇到错误
Role
|> Repo.get(id)
|> Repo.delete
错误是:
** (Ecto.ConstraintError) constraint error when attempting to delete struct:
* foreign_key: users_role_id_fkey
If you would like to convert this constraint into an error, please
call foreign_key_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:
* foreign_key: roles_users_fkey
我不知道如何在删除时添加这个foreign_key_constraint。我试着自己写,比如:
def delete_changeset(struct) do
struct
|> cast(%{}, [])
|> foreign_key_constraint(:users)
end
并在|> Repo.delete 之前插入它。但它不起作用。如何在此处添加foreign_key_constraint?
更新
迁移文件:
defmodule MyApp.Repo.Migrations.CreateRole do
use Ecto.Migration
def change do
create table(:roles) do
add :name, :string, null: false
timestamps()
end
create unique_index(:roles, [:name])
end
end
给用户添加role_id:
defmodule MyApp.Repo.Migrations.AddRoleIdToUsers do
use Ecto.Migration
def up do
alter table(:users) do
add :role_id, references(:roles, on_delete: :nothing)
remove :role
end
end
end
【问题讨论】:
-
|> foreign_key_constraint(:roles)? -
不幸的是,它不起作用。同样的错误信息
-
能否请您包含用于生成这些表的迁移文件?
-
亲爱的@Dogbert,完成!
-
|> assoc_constraint(:role)(没有foreign_key_constraint)怎么样?