Search code examples
ruby-on-railscallbackassociationsdestroy

Ruby on Rails - Association gets deleted before "before_destroy"


I have an object A that has_many B's (simple association):

has_many :book_accounts, {
    dependent: :destroy
}

I was working on a before_destroy callback. I want to check and make sure that there are no C's (which belongs_to B) and D's (which belongs_to C) before destroying the A. I checked the log and all of the B's are getting deleted before the callback causing the callback to crash.

Is this how Rails is supposed to work? Is there something I can do other than removing the dependent: destroy and manually destroying the B's in an after_destroy callback? Or is that the go-to solution?


Solution

  • This is a very silly problem of rails & frustrating too. When you define a relationship in Rails, the :dependent option actually creates a callback. If you define a before_destroy callback after the relationship, then your callback isn't called until the relationships are destroyed.

    The solution is to order your before_destroy callback before the declaration of the association.

    Your code will be something like this

    Class A < ActiveRecord::Base
      before_destroy :check
    
      has_many :book_accounts, dependent: :destroy
    End