From 0d4876537bf86394d1c24731a3a985ba832cbebd Mon Sep 17 00:00:00 2001 From: Ivan Ukhov Date: Sat, 20 Nov 2010 18:03:52 +0300 Subject: [PATCH] Make the :dependent option work in case of through associations --- .../associations/has_many_through_association.rb | 27 +++++++++++++++++--- .../associations/through_association_scope.rb | 8 +++--- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 79c229d..0161faf 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -71,11 +71,30 @@ module ActiveRecord through_association.create!(construct_join_attributes(record)) end - # TODO - add dependent option support + # Deletes the records according to the :dependent option. def delete_records(records) - klass = @reflection.through_reflection.klass - records.each do |associate| - klass.delete_all(construct_join_attributes(associate)) + reflection = @reflection.through_reflection + klass = reflection.klass + case reflection.options[:dependent] + when :destroy + records.each do |associate| + attributes = construct_join_attributes associate + klass.where(attributes).each { |record| record.destroy } + end + when :delete_all + records.each do |associate| + attributes = construct_join_attributes associate + klass.delete_all attributes + end + else + nullified = 0 + records.each do |associate| + attributes = construct_join_attributes associate + nullified_attributes = construct_owner_attributes(reflection, true) + nullified += klass.where(attributes).count if has_cached_counter? + klass.where(attributes).update(nullified_attributes) + end + @owner.class.update_counters(@owner.id, cached_counter_attribute_name => -nullified) if has_cached_counter? end end diff --git a/activerecord/lib/active_record/associations/through_association_scope.rb b/activerecord/lib/active_record/associations/through_association_scope.rb index bd8e304..ad91e43 100644 --- a/activerecord/lib/active_record/associations/through_association_scope.rb +++ b/activerecord/lib/active_record/associations/through_association_scope.rb @@ -85,12 +85,12 @@ module ActiveRecord end # Construct attributes for associate pointing to owner. - def construct_owner_attributes(reflection) + def construct_owner_attributes(reflection, nullify = false) if as = reflection.options[:as] - { "#{as}_id" => @owner.id, - "#{as}_type" => @owner.class.base_class.name.to_s } + { "#{as}_id" => nullify ? nil : @owner.id, + "#{as}_type" => nullify ? nil : @owner.class.base_class.name.to_s } else - { reflection.primary_key_name => @owner.id } + { reflection.primary_key_name => nullify ? nil : @owner.id } end end -- 1.6.2.2