Permalink
Browse files

cleanup `update/reset_counters`: less SQL strings, more ActiveRecord/…

…Arel
  • Loading branch information...
1 parent 533b131 commit d2ec9fd397d13f48b3533c900d6af86c16df866e @mislav mislav committed with mikel Apr 16, 2010
Showing with 8 additions and 12 deletions.
  1. +8 −12 activerecord/lib/active_record/counter_cache.rb
View
20 activerecord/lib/active_record/counter_cache.rb
@@ -19,7 +19,9 @@ def reset_counters(id, *counters)
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 @@ def reset_counters(id, *counters)
# # 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.

0 comments on commit d2ec9fd

Please sign in to comment.