ActiveRecord DeleteRestrictionError

Page.rb

has_many :comments, :dependent => :restrict 

This check boosts

 PagesController# (ActiveRecord::DeleteRestrictionError) "Cannot delete record because of `dependent comments"` 

Is there a way to show it as a flash message or other verification messages.?

+4
source share
2 answers

Use start / rescue to catch this exception, and then add the error message to the base errors for the page ... my syntax is off, but something like ...

 begin @page.destroy rescue ActiveRecord::DeleteRestrictionError => e @page.errors.add(:base, e) end 
+14
source

You can also deal with it in the application controller if you do not want to run recovery units on many of your controllers.

Controllers / application _controller.rb

 rescue_from ActiveRecord::DeleteRestrictionError do |exception| redirect_to(:back, :alert => exception.message) end 

It will redirect the page or resource from which the request came and display a warning message.

+4
source

All Articles