Rails: 如何在 rails 中使用 dependent: :destroy?

Rails: How to use dependent: :destroy in rails?

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

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

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

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".

我错过了什么?

删除群组时,您使用的是删除还是销毁。 - 我以前遇到过这个错误,那是因为我打错了,使用的是 .delete 而不是 .destroy

:dependentbelongs_to association

中可用的选项之一
If you set the :dependent option to:

:destroy, when the object is destroyed, destroy will be called on its associated objects.
:delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.

Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :delete_all.

在has_many 协会:

:destroy causes all the associated objects to also be destroyed
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)

你可以试试

 emp_member_1= @emp_group.emp_group_members.first
 ##delete associated record
 @emp_group.emp_group_members.delete(emp_member_1)

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

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

您是在调用 delete 方法吗?您应该改为调用 destroy。 使用 .destroy

新语法:

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

像这样插入关系

has_many :children, :dependent => :destroy

要了解有关销毁和删除的更多信息,请转到此 link https://medium.com/@wkhearn/delete-vs-destroy-does-it-even-matter-8cb4db6aa660