我有以下课程:
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中的实现已经改变了。关于如何让它工作的任何要点?
修改
我最终想要的是,一次性软删除一个类别和所有相关产品。这可能吗?或者是否会在之前的destroy回调中迭代每个Product对象? (最后一个选项)
答案 0 :(得分:1)
你应该从你的destroy方法中调用super:
def destroy
super
puts "Category destroy"
end
但我绝对不会建议你覆盖活跃的模型方法。
答案 1 :(得分:1)
所以这就是我最终做到的:
class Product < ApplicationRecord
belongs_to :product_category
def destroy
run_callbacks :destroy do
update_attribute(:deleted_at, Time.now)
# return true to escape exception being raised for rollback
true
end
end
end
class ProductCategory < ApplicationRecord
has_many :products, dependent: :destroy
def destroy
# run all callback around the destory method
run_callbacks :destroy do
update_attribute(:deleted_at, Time.now)
# return true to escape exception being raised for rollback
true
end
end
end
我从destroy返回true确实使update_attribute有点危险,但我也在ApplicationController级别捕获异常,所以对我们来说效果很好。