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.?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With