简体   繁体   English

如何修改依赖项::destroy in rails

[英]How to modify dependent: :destroy in rails

If I have two models, Model1 and Model2 as follows 如果我有两个模型,则Model1Model2如下

class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy
end

and

class Model2 < ActiveRecord::Base
  belongs :model1
end

I want to increase the destroy capability when I destroy a record in Model1 . 我想在销毁Model1的记录时提高销毁能力。 As well as the dependent records, I want to destroy Model2 records that meet an attribute test as well. 除了相关记录之外,我还想销毁同时满足属性测试的Model2记录。 How can this be done? 如何才能做到这一点?

You can use Active Record Callbacks to solve your problem. 您可以使用Active Record回调来解决您的问题。 after_destroy may help you. after_destroy可能会对您有所帮助。

class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy

  after_destroy :increase_the_destroy_capability

  private

  def increase_the_destroy_capability
    # do some thing
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM