instance method update_counters

Ruby on Rails 7.2.3

Since v4.0.13

Available in: v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

update_counters(id, counters)

A generic “counter updater” implementation, intended primarily to be used by #increment_counter and #decrement_counter, but which may also be useful on its own. It simply does a direct SQL update for the record with the given ID, altering the given hash of counters by the amount given by the corresponding value:

Parameters

  • id - The id of the object you wish to update a counter on or an array of ids.

  • counters - A Hash containing the names of the fields to update as keys and the amount to update the field by as values.

  • :touch option - Touch timestamp columns when updating. If attribute names are passed, they are updated along with updated_at/on attributes.

Examples

# For the Post with id of 5, decrement the comments_count by 1, and
# increment the actions_count by 1
Post.update_counters 5, comments_count: -1, actions_count: 1
# Executes the following SQL:
# UPDATE posts
#    SET comments_count = COALESCE(comments_count, 0) - 1,
#        actions_count = COALESCE(actions_count, 0) + 1
#  WHERE id = 5

# For the Posts with id of 10 and 15, increment the comments_count by 1
Post.update_counters [10, 15], comments_count: 1
# Executes the following SQL:
# UPDATE posts
#    SET comments_count = COALESCE(comments_count, 0) + 1
#  WHERE id IN (10, 15)

# For the Posts with id of 10 and 15, increment the comments_count by 1
# and update the updated_at value for each counter.
Post.update_counters [10, 15], comments_count: 1, touch: true
# Executes the following SQL:
# UPDATE posts
#    SET comments_count = COALESCE(comments_count, 0) + 1,
#    `updated_at` = '2016-10-13T09:59:23-05:00'
#  WHERE id IN (10, 15)

Parameters

id req
counters req
Source
# File activerecord/lib/active_record/counter_cache.rb, line 115
      def update_counters(id, counters)
        id = [id] if composite_primary_key? && id.is_a?(Array) && !id[0].is_a?(Array)
        unscoped.where!(primary_key => id).update_counters(counters)
      end

Defined in activerecord/lib/active_record/counter_cache.rb line 115 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::CounterCache::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close