instance method
update_counters
Ruby on Rails 7.0.10
Since v6.1.7.10Signature
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. -
:touchoption - 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
-
countersreq
Source
# File activerecord/lib/active_record/relation.rb, line 516
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 516
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Relation