validate before_destroy
January 12th, 2009
Recently I had to look at various options to do proper validation before destroying a model. Rails doesn't have a validate_before_destroy callback but it does have before_destroy.
We could implement a simple validation before destroy two ways:
Option 1: Implement the callback before_destroy in the model class itself.
Implement the method before_destroy in the model code itself.
1 2 3 4 5 6 7 8 |
class Organization < ActiveRecord::Base def before_destroy # Do your thing # Return true or false self.expired? end end |
From the rails documentation
Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.
So with that said, any associations that are defined in the model would be destroyed before model.destroy call is aborted and there no way of going back.
Option 2: Register the callback before_destroy at the top of the method
In your model code declare at the top
1 2 3 4 5 6 7 8 9 10 |
class Organization < ActiveRecord::Base before_destroy :okToDelete protected def okToDelete # Do your thing # Return true or false self.expired? end end |
In this case, if you define the callback at the very top of the model class (before any other association declaration), then rails makes sure to call this callback first and aborts the destroy call.
You can also pass a block to the callback to keep it simple.
1 2 3 4 5 6 7 8 |
class Organization < ActiveRecord::Base before_destroy do |r| # Do your thing # Return true or false r.expired? end end |
or even less
1 2 3 4 |
class Organization < ActiveRecord::Base before_destroy {|r| r.expired?} end |



January 27th, 2009 at 09:48 PM Great! Thank you very much! I always wanted to write in my blog something like that. Can I take part of your post to my blog? Of course, I will add backlink? Sincerely, Timur Alhimenkov