0

I'm using ActiveRecord in rails and I have a model named Menu, many other models belong to Menu: Ingredient, Product, ProductSize, Category, ...

And to those models other models belong to: ProductPrice belongs to Product, ...

I have an attribute named version:integer in Menu. what would the cleanest approach be to increase this integer every time model that belongs_to that menu is inserted/deleted/edited? I could probably solve this with an after_save callback in the child models but I'm not sure it that would be the best approach.

Edit: using Parandroid tip I came up with this:

class MenuObserver < ActiveRecord::Observer
  observe :ingredient, :product, :menu_category, :ingredient_category, :product_type, :product_size, :product_price

  def after_save(model)
    model.menu.version = model.menu.version + 1;
    model.menu.save!
  end
end

Which works perfectly.

4

2 回答 2

0

after_save回调可能是您最干净的方法。您还可以执行方法覆盖。

def update_attributes
    self.version += 1
    super
end

但我相信anafter_save更好

于 2013-05-16T22:49:19.337 回答
0

我认为观察者可以帮助你。看那个链接!.

于 2013-05-16T23:03:57.677 回答