module ActiveRecord::CounterCache::ClassMethods
def update_counters(id, counters)
# SET comment_count = COALESCE(comment_count, 0) + 1
# UPDATE posts
# Executes the following SQL:
Post.update_counters [10, 15], comment_count: 1
# For the Posts with id of 10 and 15, increment the comment_count by 1
# WHERE id = 5
# action_count = COALESCE(action_count, 0) + 1
# SET comment_count = COALESCE(comment_count, 0) - 1,
# UPDATE posts
# Executes the following SQL:
Post.update_counters 5, comment_count: -1, action_count: 1
# increment the action_count by 1
# For the Post with id of 5, decrement the comment_count by 1, and
==== Examples
to update as keys and the amount to update the field by as values.
* +counters+ - A Hash containing the names of the fields
* +id+ - The id of the object you wish to update a counter on or an Array of ids.
==== Parameters
given by the corresponding value:
with the given ID, altering the given hash of counters by the amount
be useful on its own. It simply does a direct SQL update for the record
used by increment_counter and decrement_counter, but which may also
A generic "counter updater" implementation, intended primarily to be
def update_counters(id, counters) updates = counters.map do |counter_name, value| operator = value < 0 ? '-' : '+' quoted_column = connection.quote_column_name(counter_name) "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}" end unscoped.where(primary_key => id).update_all updates.join(', ') end