Isaac
Isaac

Reputation: 2364

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?

Upvotes: 20

Views: 4838

Answers (2)

Jonas
Jonas

Reputation: 5149

Have to add prepend: true to callback declaration:

before_destroy :do_something_before_children_removed, prepend: true

Upvotes: 25

Sajid Rabbani
Sajid Rabbani

Reputation: 401

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

Upvotes: 33

Related Questions