Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord CounterCache and Callbacks

Does counter_cache increments and decrements fire active_record callbacks ?

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

In the above code will the function do_something be called when a new cup is added and it belongs to a user, update will be called on that user to update the cups_count, but from what I have tried it seems like the counter_cache updates don't fire callbacks, may be because they are themselves inside callbacks ?

Thanks

like image 907
Abid Avatar asked Feb 16 '23 16:02

Abid


1 Answers

From the source for counter cache, it seems that ActiveRecord is doing a direct database update, which will skip callbacks.

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

According to the documentation for update_all, it does skip callbacks.

like image 149
davogones Avatar answered Feb 19 '23 06:02

davogones