Skip to content

Commit b177427

Browse files
committed
Fix update counters of multiple records with touch: true
Currently does not work the following example in the doc: ```ruby # For the Posts with id of 10 and 15, increment the comment_count by 1 # and update the updated_at value for each counter. Post.update_counters [10, 15], comment_count: 1, touch: true # Executes the following SQL: # UPDATE posts # SET comment_count = COALESCE(comment_count, 0) + 1, # `updated_at` = '2016-10-13T09:59:23-05:00' # WHERE id IN (10, 15) ```
1 parent 4a36d81 commit b177427

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

activerecord/lib/active_record/counter_cache.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def update_counters(id, counters)
105105
end
106106

107107
if touch
108-
object = find(id)
108+
object = find(id.is_a?(Array) ? id.first : id)
109109
updates << object.class.send(:sanitize_sql_for_assignment, touch_updates(object, touch))
110110
end
111111

activerecord/test/cases/counter_cache_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,16 @@ class ::SpecialReply < ::Reply
227227
end
228228
end
229229

230+
test "update counters of multiple records with touch: true" do
231+
t1, t2 = topics(:first, :second)
232+
233+
assert_touching t1, :updated_at do
234+
assert_difference ["t1.reload.replies_count", "t2.reload.replies_count"], 2 do
235+
Topic.update_counters([t1.id, t2.id], replies_count: 2, touch: true)
236+
end
237+
end
238+
end
239+
230240
test "update multiple counters with touch: true" do
231241
assert_touching @topic, :updated_at do
232242
Topic.update_counters(@topic.id, replies_count: 2, unique_replies_count: 2, touch: true)

0 commit comments

Comments
 (0)