aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMislav Marohnić <mislav.marohnic@gmail.com>2010-04-16 23:31:38 +0200
committerMikel Lindsaar <raasdnil@gmail.com>2010-06-03 23:32:09 +1000
commitd2ec9fd397d13f48b3533c900d6af86c16df866e (patch)
tree77d221e8a54966a0d6e5535b316eb567b3d21298
parent533b1311b082aab52d2fccebae03bb74c406f8be (diff)
downloadrails-d2ec9fd397d13f48b3533c900d6af86c16df866e.tar.gz
rails-d2ec9fd397d13f48b3533c900d6af86c16df866e.tar.bz2
rails-d2ec9fd397d13f48b3533c900d6af86c16df866e.zip
cleanup `update/reset_counters`: less SQL strings, more ActiveRecord/Arel
-rw-r--r--activerecord/lib/active_record/counter_cache.rb20
1 files changed, 8 insertions, 12 deletions
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.