diff options
author | Gabe da Silveira <gabe@websaviour.com> | 2009-12-02 15:28:54 -0800 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-12-03 23:25:11 -0800 |
commit | 32395899d7c97f69b508b7d7f9b7711f28586679 (patch) | |
tree | ca1ca850101571c2251334a991ff7a419e9cfbc4 /activerecord/lib/active_record | |
parent | e55284e8256461fc2440c41548ee9b4216f96b47 (diff) | |
download | rails-32395899d7c97f69b508b7d7f9b7711f28586679.tar.gz rails-32395899d7c97f69b508b7d7f9b7711f28586679.tar.bz2 rails-32395899d7c97f69b508b7d7f9b7711f28586679.zip |
Replace reset_counter_cache with reset_counters that has API inline with existing update_counters method
[#1211 state:committed]
Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
Diffstat (limited to 'activerecord/lib/active_record')
-rwxr-xr-x | activerecord/lib/active_record/base.rb | 21 |
1 files changed, 13 insertions, 8 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index e04684dc43..321bba466e 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -967,20 +967,25 @@ module ActiveRecord #:nodoc: connection.select_value(sql, "#{name} Count").to_i end - # Reset a counter cache for all records. + # Resets one or more counter caches to their correct value using an SQL + # count query. This is useful when adding new counter caches, or if the + # counter has been corrupted or modified directly by SQL. # # ==== Parameters # - # * +association_name+ - The name of of the association counter cache to reset + # * +id+ - The id of the object you wish to reset a counter on. + # * +counters+ - One or more counter names to reset # # ==== Examples - # # For all Post records reset the comments_count - # Post.reset_counter_cache(:comments) - def reset_counter_cache(association) - child_class = reflect_on_association(association).klass - counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column + # + # # For Post with id #1 records reset the comments_count + # Post.reset_counters(1, :comments) + def reset_counters(id, *counters) + object = find(id) + counters.each do |association| + child_class = reflect_on_association(association).klass + counter_name = child_class.reflect_on_association(self.name.downcase.to_sym).counter_cache_column - find_each do |object| 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") end end |