First keep in mind that :dependent => :destroy
hooks into before_destroy
.
So when you use other before_destroy
callbacks the sequential arrangement of your code may be important.
For example:
class Container < ActiveRecord::Base
before_destroy :a_callback
has_many :items, :dependent => :destroy
end
results in
container.destroy
# => a_callback
# => container.items.destroy_all
but
class Container < ActiveRecord::Base
has_many :items, :dependent => :destroy
before_destroy :a_callback
end
ends up in
container.destroy
# => container.items.destroy_all
# => a_callback
Furthermore: Issues when destroying cached objects
def change_container_before_destruction(other_container)
item.container == container_1
item.container = other_container
item.save
container_1.destroy
end
results in
# => item gets destroyed because ":dependent => :destroy" operates on cache
but to reach the intended effect you must reload the object:
def change_container_before_destruction(other_container)
item.container == container_1
item.container = other_container
item.save
item.reload # <=
container_1.destroy
end
now item
is not destroyed.
Posted by Martin Straub to makandra dev (2011-10-21 13:13)