Ruby on Rails - Association gets deleted before "before_destroy"
Asked Answered
L

2

20

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?

Lieselotteliestal answered 10/7, 2015 at 14:33 Comment(1)
See the discussion here: github.com/rails/rails/issues/3458Salish
P
33

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
Psalter answered 10/7, 2015 at 15:11 Comment(1)
I actually just found that out too (github.com/rails/rails/issues/3458) , and was in the process of answering the question when you answered. Thank you!Lieselotteliestal
W
24

Have to add prepend: true to callback declaration:

before_destroy :do_something_before_children_removed, prepend: true
Winsor answered 20/9, 2017 at 7:15 Comment(2)
Link for docs: api.rubyonrails.org/classes/ActiveRecord/…Melbourne
This is probably the best right answerPallium

© 2022 - 2024 — McMap. All rights reserved.