From 16b129a68ca1770815107a3edb54090282349ba7 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 19 Jan 2008 05:30:42 +0000 Subject: belongs_to supports :dependent => :destroy and :delete. Closes #10592. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8675 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/lib/active_record/associations.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 4743d3be8f..3692be3aeb 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -792,6 +792,10 @@ module ActiveRecord # * :foreign_key - specify the foreign key used for the association. By default this is guessed to be the name # of the association with an +_id+ suffix. So a class that defines a +belongs_to :person+ association will use +person_id+ as the default +foreign_key+. # Similarly, +belongs_to :favorite_person, :class_name => "Person"+ will use a foreign key of +favorite_person_id+. + # * :dependent - if set to :destroy, the associated object is destroyed when this object is. If set to + # :delete, the associated object is deleted *without* calling its destroy method. This option should not be specified when + # belongs_to is used in conjunction with a has_many relationship on another class because of the potential to leave + # orphaned records behind. # * :counter_cache - caches the number of belonging objects on the associate class through the 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) @@ -876,6 +880,8 @@ module ActiveRecord "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)" ) end + + configure_dependency_for_belongs_to(reflection) end # Associates two classes via an intermediate join table. Unless the join table is explicitly specified as @@ -1202,6 +1208,19 @@ module ActiveRecord end end + def configure_dependency_for_belongs_to(reflection) + if reflection.options.include?(:dependent) + case reflection.options[:dependent] + when :destroy + module_eval "before_destroy '#{reflection.name}.destroy unless #{reflection.name}.nil?'" + when :delete + module_eval "before_destroy '#{reflection.class_name}.delete(#{reflection.name}.id) unless #{reflection.name}.nil?'" + else + raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{reflection.options[:dependent].inspect})" + end + end + end + def create_has_many_reflection(association_id, options, &extension) options.assert_valid_keys( :class_name, :table_name, :foreign_key, -- cgit v1.2.3