From f493f31533cf8db7756be8ed62a749ed57b7c7cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 16 Apr 2010 23:31:38 +0200 Subject: cleanup `update/reset_counters`: less SQL strings, more ActiveRecord/Arel --- activerecord/lib/active_record/counter_cache.rb | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index cbebded995..3bdb6970f8 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -19,7 +19,9 @@ module ActiveRecord child_class = reflect_on_association(association).klass counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column - connection.update("UPDATE #{quoted_table_name} SET #{connection.quote_column_name(counter_name)} = #{object.send(association).count} WHERE #{connection.quote_column_name(primary_key)} = #{quote_value(object.id)}", "#{name} UPDATE") + self.unscoped.where(arel_table[self.primary_key].eq(object.id)).arel.update( + arel_table[counter_name] => object.send(association).count + ) end end @@ -53,19 +55,13 @@ module ActiveRecord # # SET comment_count = comment_count + 1, # # WHERE id IN (10, 15) def update_counters(id, counters) - updates = counters.inject([]) { |list, (counter_name, increment)| - sign = increment < 0 ? "-" : "+" - list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}" - }.join(", ") - - if id.is_a?(Array) - ids_list = id.map {|i| quote_value(i)}.join(', ') - condition = "IN (#{ids_list})" - else - condition = "= #{quote_value(id)}" + updates = counters.map do |counter_name, value| + operator = value < 0 ? '-' : '+' + quoted_column = connection.quote_column_name(counter_name) + "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}" end - update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}") + update_all(updates.join(', '), primary_key => id ) end # Increment a number field by one, usually representing a count. -- cgit v1.2.3