Ruby-on-rails 如何在 rails 中使用依赖::destroy?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29560805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:11:27  来源:igfitidea点击:

How to use dependent: :destroy in rails?

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4ruby-on-rails-3.2

提问by sank

I have 2 models as describes below.

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

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

and

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

What I'm missing?

我缺少什么?

采纳答案by Umar Khan

Add cascading delete to your EmpGroup model:

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

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

Or

或者

Are you calling deletemethod? you should call destroyinstead. Use .destroy

你在调用delete方法吗?你应该打电话destroy。用.destroy

回答by Milind

:dependentis one of the options available in belongs_toassociation

:dependentbelongs_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::删除所有。

in has_manyassociations:

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

you can try

你可以试试

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

回答by abbott567

When you delete a group, are you using delete or destroy. - I've had this error before, and it was because I had a typo and was using .delete instead of .destroy

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

回答by Thomas Van Holder

New syntax:

新语法:

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