我有2个模型,User
和Role
。 User
has_many
Roles
。我也设置了外键约束(如果有任何具有此角色的用户,则无法删除角色。)
我在尝试实施
时遇到错误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
答案 0 :(得分:2)
我通过
解决了这个问题|> foreign_key_constraint(:users, name: :users_role_id_fkey)
删除更改集中的。但它返回了可怕的错误
%{ "users" => ["doesn't exist"] }
变更集中的。我勒个去?我想在变更集中有正确的错误
答案 1 :(得分:1)
Role
|> Repo.get(id)
|> Ecto.Changeset.change
|> Ecto.Changeset.no_assoc_constraint(:users)
|> Repo.delete