Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
Isaac Avatar asked Jul 10 '15 14:07

Isaac


2 Answers

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
like image 104
Sajid Rabbani Avatar answered Oct 12 '22 13:10

Sajid Rabbani


Have to add prepend: true to callback declaration:

before_destroy :do_something_before_children_removed, prepend: true
like image 28
Jonas Avatar answered Oct 12 '22 15:10

Jonas