每当更新计数器缓存时,Rails 中有没有办法调用函数?
问问题
180 次
1 回答
1
没有办法开箱即用。您可以轻松地制作一个添加该功能的 Gem。从 after_create 和 after_destroy 回调手动更新计数器可能更容易,这也可以执行您需要的任何其他代码。
例如:
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
于 2012-04-24T13:03:46.003 回答