1

我有一个类别模型,它与说 category_supply 和 category_experience 模型有关联。如果类别模型或其关联模型(category_supply 和 category_experience)有任何变化,它应该调用 after_save。这样我就不需要在每个模型中写 after_save

4

1 回答 1

0

您可以使用 anActiveRecord::Observer来观察关联模型的变化,然后触发父模型的回调。这是一个例子:

class CategoryAssociationsObserver < ActiveRecord::Observer
  observe Supply, Experience
  def after_save(record)
    record.category.run_callbacks(:save) if record.category
    # I don't know if you can trigger just the `after_save` callback here
  end
end

有关其使用的更多信息,请参阅ActiveRecord::Observer文档:http: //apidock.com/rails/ActiveRecord/Observer

于 2013-07-17T17:13:03.060 回答