From ff881c7f8b1ffd855c09cabcd2c9b06aea4e850d Mon Sep 17 00:00:00 2001 From: Jamis Buck Date: Sat, 4 Mar 2006 19:42:41 +0000 Subject: Make counter cache work when replacing an association (closes #3245). Thanks for the patch! git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3762 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- .../lib/active_record/associations/belongs_to_association.rb | 11 +++++++++++ activerecord/lib/active_record/reflection.rb | 8 ++++++++ 2 files changed, 19 insertions(+) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 804a7ebf21..3e0e0d0fb9 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -10,11 +10,22 @@ module ActiveRecord end def replace(record) + counter_cache_name = @reflection.counter_cache_column + if record.nil? + if counter_cache_name && @owner[counter_cache_name] && !@owner.new_record? + @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name] + end + @target = @owner[@reflection.primary_key_name] = nil else raise_on_type_mismatch(record) + if counter_cache_name && @owner[counter_cache_name] && !@owner.new_record? + @reflection.klass.increment_counter(counter_cache_name, record.id) + @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name] + end + @target = (AssociationProxy === record ? record.target : record) @owner[@reflection.primary_key_name] = record.id unless record.new_record? @updated = true diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index b9369feeb7..32e812a86a 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -131,6 +131,14 @@ module ActiveRecord @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key end + def counter_cache_column + if options[:counter_cache] == true + "#{active_record.name.underscore.pluralize}_count" + elsif options[:counter_cache] + options[:counter_cache] + end + end + private def name_to_class_name(name) if name =~ /::/ -- cgit v1.2.3