aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/counter_cache.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/counter_cache.rb')
-rw-r--r--activerecord/lib/active_record/counter_cache.rb11
1 files changed, 7 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 237cd56683..7839f03848 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -30,9 +30,10 @@ module ActiveRecord
reflection = belongs_to.find { |e| e.class_name == expected_name }
counter_name = reflection.counter_cache_column
- self.unscoped.where(arel_table[self.primary_key].eq(object.id)).arel.update({
+ stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
arel_table[counter_name] => object.send(association).count
})
+ connection.update stmt.to_sql
end
return true
end
@@ -56,15 +57,15 @@ module ActiveRecord
# Post.update_counters 5, :comment_count => -1, :action_count => 1
# # Executes the following SQL:
# # UPDATE posts
- # # SET comment_count = comment_count - 1,
- # # action_count = action_count + 1
+ # # SET comment_count = COALESCE(comment_count, 0) - 1,
+ # # action_count = COALESCE(action_count, 0) + 1
# # WHERE id = 5
#
# # For the Posts with id of 10 and 15, increment the comment_count by 1
# Post.update_counters [10, 15], :comment_count => 1
# # Executes the following SQL:
# # UPDATE posts
- # # SET comment_count = comment_count + 1,
+ # # SET comment_count = COALESCE(comment_count, 0) + 1,
# # WHERE id IN (10, 15)
def update_counters(id, counters)
updates = counters.map do |counter_name, value|
@@ -73,6 +74,8 @@ module ActiveRecord
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
end
+ IdentityMap.remove_by_id(symbolized_base_class, id) if IdentityMap.enabled?
+
update_all(updates.join(', '), primary_key => id )
end