我有以下類別: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