如何使用依赖::在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". 

我错过了什么?

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

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

要么

你在调用delete方法吗? 你应该调用destroy来代替。 使用.destroy

:dependent是belongs_to关联中可用的选项之一

 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 Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent:

在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) 

删除组时,是使用删除还是销毁。 – 我以前遇到过这个错误,这是因为我有一个错字并使用.delete而不是.destroy