2016-06-08 52 views
1

我有以下类别: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回调? (对我最后的选项)

+0

删除你的两个销毁方法,然后再试一次。 –

+0

它在我看来你是过度active_model销毁方法,并且你应该在销毁中调用“超级”? –

+0

我真的不建议覆盖ActiveRecord方法。使自己像'update_as_destroyed'和'update_as_destroyed_all'而不是覆盖现有的。 – Kkulikovskis

回答

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 

我从返回true的破坏确实让update_attribute有点危险,但我在ApplicationController中级别捕获异常一样,所以效果很好为了我们。

0

您应该从销毁方法调用超:

def destroy 
    super 
    puts "Category destroy" 
end 

但是我绝对不会建议你在此改变主动型方法。

+0

它不会工作,因为记录仍然会被销毁。他不想要那 – Kkulikovskis

+0

是的,这就是他想要做的,但我的回答指的是他的问题,这就是为什么dependent :: destroy不起作用。他并没有要求如何实施他想要做的更新。 –

+0

是的,我编辑了我的问题。 –