1

Ruby 2.1.2 and Rails 4: I have a parent object and a child object. I have a before_destroy callback for the child object that may prevent its destruction based on a flag. However, I also need its parent to be able to destroy it via a dependent: :destroy relationship.

How can I check the source of its destruction in my validation?

I found marked_for_destruction? and a host of related questions here, but none seem concerned with the before_destroy callback, which runs before the object (or even its parent) are marked for destruction. I've been prying through what's accessible in the callback for a while now and can't seem to find anything.

I could obviously go with dependent: :delete instead, although that seems like it misses the point. I'm sure I could come up with something else like doing a before_destroy on the parent, and then calling a monkey-patched destroy method with some arguments or some such thing, but it also seems to miss the point.

Any suggestions? Is there some property on the parent that I'm missing, or a way to trace the destroy call's source or something? Thanks in advance!

jack_was_taken
  • 939
  • 1
  • 7
  • 17
  • 1
    You might find hints here: http://www.moncefbelyamani.com/rails-prevent-the-destruction-of-child-object-when-parent-requires-its-presence/ – oldergod Nov 20 '14 at 00:38
  • 1
    Looks like this prior question takes the `before_destroy` approach you mention: http://stackoverflow.com/questions/21578812/in-rails-how-to-determine-if-a-record-was-destroyed-by-a-dependent-destroy-ca – tvalent2 Nov 20 '14 at 03:29
  • One more quick thing: according to the [docs](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html), `:dependent` "is implemented using Rails' callback system" so placement of other filters around it may cause odd behavior. – tvalent2 Nov 20 '14 at 03:38
  • Both super helpful, thank you both very much. – jack_was_taken Nov 20 '14 at 16:30

0 Answers0