aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record
diff options
context:
space:
mode:
authorRafael Mendonça França <rafaelmfranca@gmail.com>2014-05-17 16:21:41 -0300
committerRafael Mendonça França <rafaelmfranca@gmail.com>2014-05-17 16:21:41 -0300
commit067131524b5b5cb6100aca8bf5b48a3006a93acd (patch)
tree365807e82aa8bae4dcecf86396fb4f53d2039b08 /activerecord/lib/active_record
parent7caf3ffffd368926f78e30a371d17a524c9fb13e (diff)
parentfec7bfe8d13b7f5a076011364cf68e6ae56f03ff (diff)
downloadrails-067131524b5b5cb6100aca8bf5b48a3006a93acd.tar.gz
rails-067131524b5b5cb6100aca8bf5b48a3006a93acd.tar.bz2
rails-067131524b5b5cb6100aca8bf5b48a3006a93acd.zip
Merge pull request #14428 from jnormore/reset_counters_alias
Updates reset_counters to allow counter name in params
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r--activerecord/lib/active_record/counter_cache.rb15
1 files changed, 10 insertions, 5 deletions
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index b7b790322a..71e176a328 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -11,7 +11,7 @@ module ActiveRecord
# ==== Parameters
#
# * +id+ - The id of the object you wish to reset a counter on.
- # * +counters+ - One or more association counters to reset
+ # * +counters+ - One or more association counters to reset. Association name or counter name can be given.
#
# ==== Examples
#
@@ -19,9 +19,14 @@ module ActiveRecord
# Post.reset_counters(1, :comments)
def reset_counters(id, *counters)
object = find(id)
- counters.each do |association|
- has_many_association = reflect_on_association(association.to_sym)
- raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association
+ counters.each do |counter_association|
+ has_many_association = reflect_on_association(counter_association.to_sym)
+ unless has_many_association
+ has_many = reflect_on_all_associations(:has_many)
+ has_many_association = has_many.find { |association| association.counter_cache_column && association.counter_cache_column.to_sym == counter_association.to_sym }
+ counter_association = has_many_association.plural_name if has_many_association
+ end
+ raise ArgumentError, "'#{self.name}' has no association called '#{counter_association}'" unless has_many_association
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
has_many_association = has_many_association.through_reflection
@@ -34,7 +39,7 @@ module ActiveRecord
counter_name = reflection.counter_cache_column
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
- arel_table[counter_name] => object.send(association).count
+ arel_table[counter_name] => object.send(counter_association).count
}, primary_key)
connection.update stmt
end