From 87898badba211540d9c1d4dae0cd513a9d525554 Mon Sep 17 00:00:00 2001 From: Jamis Buck Date: Thu, 9 Mar 2006 17:23:57 +0000 Subject: Allow counter_cache to accept a column name git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3825 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/lib/active_record/associations.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index b25df26059..a098c0f326 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -460,7 +460,8 @@ module ActiveRecord # * :counter_cache - caches the number of belonging objects on the associate class through use of increment_counter # and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it's # destroyed. This requires that a column named "#{table_name}_count" (such as comments_count for a belonging Comment class) - # is used on the associate class (such as a Post class). + # is used on the associate class (such as a Post class). You can also specify a custom counter cache column by given that + # name instead of a true/false value to this option (e.g., :counter_cache => :my_custom_counter.) # * :include - specify second-order associations that should be eager loaded when this object is loaded. # # Option examples: @@ -515,13 +516,17 @@ module ActiveRecord end if options[:counter_cache] + cache_column = options[:counter_cache] == true ? + "#{self.to_s.underscore.pluralize}_count" : + options[:counter_cache] + module_eval( - "after_create '#{reflection.name}.class.increment_counter(\"#{self.to_s.underscore.pluralize + "_count"}\", #{reflection.primary_key_name})" + + "after_create '#{reflection.name}.class.increment_counter(\"#{cache_column}\", #{reflection.primary_key_name})" + " unless #{reflection.name}.nil?'" ) module_eval( - "before_destroy '#{reflection.name}.class.decrement_counter(\"#{self.to_s.underscore.pluralize + "_count"}\", #{reflection.primary_key_name})" + + "before_destroy '#{reflection.name}.class.decrement_counter(\"#{cache_column}\", #{reflection.primary_key_name})" + " unless #{reflection.name}.nil?'" ) end -- cgit v1.2.3