更新计数器缓存后的调用方法

时间:2012-04-23 16:30:46

标签: ruby-on-rails ruby-on-rails-3

每当计数器缓存更新时,Rails中是否有一种方法可以调用函数?

1 个答案:

答案 0 :(得分:1)

没有办法开箱即用。您可以制作一个Gem,添加该功能而不会有太多麻烦。从after_create和after_destroy回调手动更新计数器可能更容易,后者也可以执行您需要的任何其他代码。

E.g:

class Parent
  has_many :kids
  # The parents table has a `kids_counter` column which acts as a counter cache.
end

class Kid
  belongs_to :parent
  after_create :hello
  after_destroy :goodbye

  def hello
    Parent.increment_counter(:kids_counter, parent_id)
    # Execute anything else you need here.
  end

  def goodbye
    Parent.decrement_counter(:kids_counter, parent_id)
    # Execute anything else you need here.
  end
end