Ruby-on-rails 删除对象销毁 Rails 上的关联记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20925494/
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
Delete associated records on object destroy Rails
提问by icherevkov
I have 2 models
我有2个模型
class Deal < ActiveRecord::Base
has_many :couponizations, dependent: :destroy
has_many :coupon_codes, through: :couponizations, source: :coupon_code, dependent: :destroy
accepts_nested_attributes_for :coupon_codes, allow_destroy: true
end
and
和
class CouponCode < ActiveRecord::Base
has_one :couponization, dependent: :destroy
has_one :deal, through: :couponization, source: :deal
which are linked by many-to-many relationship
由多对多关系链接
class Couponization < ActiveRecord::Base
belongs_to :coupon_code
belongs_to :deal
end
Despite I specified dependent: :destroyoption, when I delete deal, coupon codes are not being deleted. However couponizations are deleted successfully. Is there any way to delete associated nested records on object destroy?
尽管我指定了dependent: :destroy选项,但当我删除交易时,优惠券代码不会被删除。但是优惠券删除成功。有没有办法在对象销毁时删除关联的嵌套记录?
回答by Baldrick
The options dependent: :destroyis ignored when using with the :through(see doc). You have to do it manually, with a before_destroycallbackfor example.
dependent: :destroy与:through(see doc)一起使用时将忽略这些选项。您必须手动执行此操作,例如使用before_destroy回调。
class Deal
before_destroy :destroy_coupon_codes
private
def destroy_coupon_codes
self.coupon_codes.destroy_all
end
end
回答by Sbbs
I recommend using :after_destroycallback, so if destroying some Dealinstance fails for whatever reason you don't end up deleting all of its CouponCodes.
我建议使用:after_destroy回调,所以如果销毁某个Deal实例由于任何原因失败,你最终不会删除它的所有CouponCodes.
Here's an :after_destroyexample that should work:
这是一个:after_destroy应该有效的示例:
after_destroy { |record|
CouponCode.destroy(record.coupon_codes.pluck(:id))
}
Make sure to remove dependent: :destroyfrom has_many :couponizationsin the Dealsmodel, because all couponizationswill now be destroyed by the has_one :couponization, dependent: :destroyin the CouponCodemodel.
确保删除dependent: :destroy从has_many :couponizations在Deals模型中,因为所有couponizations现在将被破坏has_one :couponization, dependent: :destroy的CouponCode模型。

