Read more

Using :dependent => :destroy – Issues with 'code arrangement' or 'cached objects'

Deleted user #6
October 21, 2011Software engineer

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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 to makandra dev (2011-10-21 15:13)