我有以下类别:Rails的5依赖:摧毁不起作用
class Product < ApplicationRecord
belongs_to :product_category
def destroy
puts "Product Destroy!"
end
end
class ProductCategory < ApplicationRecord
has_many :products, dependent: :destroy
def destroy
puts "Category Destroy!"
end
end
在这里,我试图重写destroy方法,我最终想要做到这一点:
update_attribute(:deleted_at, Time.now)
当我运行在Rails的控制台下面的语句:ProductCategory.destroy_all
我得到以下输出
Category Destroy!
Category Destroy!
Category Destroy!
注:I H每个类别都有一个以上的产品。我可以通过ProductCategory.find(1).products
来确认,它返回一系列产品。我听说Rails 5中的实现发生了变化。关于如何让这个工作起作用的任何观点?
编辑
我最终想要的,软删除类别和一气呵成的所有相关产品。这可能吗?或者将会在每个产品对象前迭代一次before destroy回调? (对我最后的选项)
删除你的两个销毁方法,然后再试一次。 –
它在我看来你是过度active_model销毁方法,并且你应该在销毁中调用“超级”? –
我真的不建议覆盖ActiveRecord方法。使自己像'update_as_destroyed'和'update_as_destroyed_all'而不是覆盖现有的。 – Kkulikovskis