instance method update_counters

Ruby on Rails 7.2.3

Since v6.1.7.10

Available in: v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

update_counters(counters)

Updates the counters of the records in the current relation.

Parameters
  • counter - A Hash containing the names of the fields to update as keys and the amount to update as values.

  • :touch option - Touch the timestamp columns when updating.

  • If attributes names are passed, they are updated along with update_at/on attributes.

Examples
# For Posts by a given author increment the comment_count by 1.
Post.where(author_id: author.id).update_counters(comment_count: 1)

Parameters

counters req
Source
# File activerecord/lib/active_record/relation.rb, line 929
    def update_counters(counters)
      touch = counters.delete(:touch)

      updates = {}
      counters.each do |counter_name, value|
        attr = table[counter_name]
        updates[attr.name] = _increment_attribute(attr, value)
      end

      if touch
        names = touch if touch != true
        names = Array.wrap(names)
        options = names.extract_options!
        touch_updates = klass.touch_attributes_with_time(*names, **options)
        updates.merge!(touch_updates) unless touch_updates.empty?
      end

      update_all updates
    end

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

Defined in ActiveRecord::Relation

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close