Rails:如何在 rails 中使用依赖::销毁? [英] Rails: How to use dependent: :destroy in rails?

查看:39
本文介绍了Rails:如何在 rails 中使用依赖::销毁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个模型,如下所述.

I have 2 models as describes below.

class EmpGroup < ActiveRecord::Base
  belongs_to :user
  has_many :emp_group_members, dependent: :destroy
end

class EmpGroupMember < ActiveRecord::Base
  belongs_to :emp_group
  belongs_to :user
end

现在的问题是,每当我试图销毁一个组时,我都会收到如下错误.

now the problem is whenever I tried to destroy a group then I received a error as below.

PG::ForeignKeyViolation: ERROR:  update or delete on table "emp_groups" violates foreign key constraint "fk_rails_bd68440021" on table "emp_group_members"
DETAIL:  Key (id)=(1) is still referenced from table "emp_group_members".

我缺少什么?

推荐答案

向您的 EmpGroup 模型添加级联删除:

Add cascading delete to your EmpGroup model:

class EmpGroup < ActiveRecord::Base
   has_many :emp_group_members, dependent: :delete_all
end

您是否正在调用 delete 方法?你应该调用 destroy 代替.使用 .destroy

Are you calling delete method? you should call destroy instead. Use .destroy

这篇关于Rails:如何在 rails 中使用依赖::销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆