rOrman
rOrman

Reputation: 133

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.?

Upvotes: 5

Views: 3556

Answers (2)

Bot
Bot

Reputation: 1011

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.

Upvotes: 8

Philip Hallstrom
Philip Hallstrom

Reputation: 19899

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

Upvotes: 16

Related Questions