4

counter_cache 递增和递减是否触发 active_record 回调?

User << AR

  has_many :cups

  after_update :do_something

  def do_something
     "Will I be called when number of cups updated ?"
  end

end

Cup << AR

   belongs_to :user, counter_cache: true

end

在上面的代码中,当添加一个新杯子并且它属于一个用户时,会调用函数 do_something,将在该用户上调用 update 来更新 cups_count,但从我尝试过的情况来看,似乎 counter_cache 更新不触发回调,可能是因为它们本身就在回调中?

谢谢

4

2 回答 2

7

从计数器缓存的来源来看,ActiveRecord 似乎正在执行直接数据库更新,这将跳过回调。

update_all(updates.join(', '), primary_key => id )

根据update_all 的文档,它确实跳过了回调。

于 2013-04-30T06:43:17.290 回答
1

正如@davogones 提到的那样,使用回调已经过时了,但是您仍然可以通过覆盖update_counters父对象中的方法来做类似的事情。

在我的情况下,如果 counter_cache 计数超过某个值,我需要做一些事情:

class Cups < ApplicationRecord
  belongs_to :user, :counter_cache => true
end

class User < ApplicationRecord
  has_many :cups

  # This will be called every time there is a counter_cache update, + or - 
  def self.update_counters(id, counters)
    user = User.find(id)
    if user.cups_count + counters['cups_count'] >= some_value
      user.do_something!
    end
    super(id, counters) # continue on with the normal update_counters flow.
  end
end

有关详细信息,请参阅update_counters 文档

于 2019-02-01T03:17:46.860 回答