aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorMislav Marohnić <mislav.marohnic@gmail.com>2010-04-16 23:31:38 +0200
committerMislav Marohnić <mislav.marohnic@gmail.com>2010-05-24 11:42:03 +0200
commitf493f31533cf8db7756be8ed62a749ed57b7c7cf (patch)
tree32f492e3dca8ce8a3b2c254a6c38279767721986 /activerecord
parent69a9669d9d51fae8f591cd7a0108b6fc4b47070c (diff)
downloadrails-f493f31533cf8db7756be8ed62a749ed57b7c7cf.tar.gz
rails-f493f31533cf8db7756be8ed62a749ed57b7c7cf.tar.bz2
rails-f493f31533cf8db7756be8ed62a749ed57b7c7cf.zip
cleanup `update/reset_counters`: less SQL strings, more ActiveRecord/Arel
Diffstat (limited to 'activerecord')
-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.