What I am trying to do is return an error, instead of an exception, when a particular model cannot be destroyed. Currently, it raises ActiveRecord::DeleteRestrictionError, but that is not returned to a flash message, or added to the errors collection of the model.
What I have done is setup this in my resourceful controller:
def destroy
begin
resource.destroy
rescue ActiveRecord::DeleteRestrictionError => e
resource.errors.add(:base, e)
end
end
I’d rather not manage this within every single controller which requires this particular behavior. How can I abstract it? I can’t see it being a good idea to overwrite the destroy method for ActiveRecord::Base, but maybe there won’t be any gotchas?
I’m using inherited_resources gem, so perhaps there is a way to answer this by extending that?
One other idea I had was to extend ActiveRecord::Base using ActiveSupport::Concern (from here: Rails extending ActiveRecord::Base) and then delegate the destroy method to a custom destroy on a model-to-model basis. Thoughts?
What I ended up doing was inheriting my controllers from a master resources controller, which I’ve found to be much cleaner and powerful than the other options discussed (found here: http://roberto.peakhut.com/2010/09/27/admin-controllers-with-inherited-resources/).
Then, simply inherit your resourceful controllers from this controller instead of ApplicationController:
Hope that helps somebody in a similar situation.