【发布时间】:2016-06-08 14:43:05
【问题描述】:
我有以下课程:
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!
注意:我有三个类别,每个类别都有多个产品。我可以通过ProductCategory.find(1).products 确认它,它返回一个产品数组。我听说 Rails 5 中的实现发生了变化。关于如何让它工作的任何要点?
编辑
我最终想要的是一次性软删除一个类别和所有相关产品。这可能吗?还是会在销毁回调之前迭代每个 Product 对象? (我的最后一个选择)
【问题讨论】:
-
删除你的两个销毁方法,然后再试一次。
-
在我看来,您正在覆盖 active_model 销毁方法,并且您应该在销毁中调用“super”?
-
我真的不建议覆盖 ActiveRecord 方法。让你自己喜欢
update_as_destroyed和update_as_destroyed_all而不是覆盖现有的。 -
听起来你想要“软删除”。 stackoverflow.com/questions/23017070/…
-
是的,我已经编辑了我的问题。
标签: ruby-on-rails rails-activerecord ruby-on-rails-5