Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord DeleteRestrictionError

Page.rb

has_many :comments, :dependent => :restrict

This validation raises

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

Is there a way to show it like a flash message or with other validation messages.?

like image 221
rOrman Avatar asked Jul 22 '11 15:07

rOrman


2 Answers

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

begin
  @page.destroy
rescue ActiveRecord::DeleteRestrictionError => e
  @page.errors.add(:base, e)
end
like image 77
Philip Hallstrom Avatar answered Oct 03 '22 07:10

Philip Hallstrom


You can also deal with it in application controller, if you don't want to put begin rescue blocks in many of your controllers.

controllers/application_controller.rb

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

It will redirect to the page or resource from which the request came and will show an alert message.

like image 34
Bot Avatar answered Oct 03 '22 08:10

Bot