Method: ActiveRecord::Relation#update_counters
- Defined in:
- activerecord/lib/active_record/relation.rb
#update_counters(counters) ⇒ Object
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: .id).update_counters(comment_count: 1)
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
# File 'activerecord/lib/active_record/relation.rb', line 919 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) = names. touch_updates = klass.touch_attributes_with_time(*names, **) updates.merge!(touch_updates) unless touch_updates.empty? end update_all updates end |