2016-06-08 47 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

是的,我編輯了我的問題。 –