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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)