开发者

ActiveRecord DeleteRestrictionError

开发者 https://www.devze.com 2023-03-22 01:55 出处:网络
Page.rb has_many :comments, :dependent => :restrict This validation raises PagesController# (ActiveRecord::DeleteRestrictionError开发者_JAVA百科) \"Cannot delete record because of `dependent co

Page.rb

has_many :comments, :dependent => :restrict

This validation raises

PagesController# (ActiveRecord::DeleteRestrictionError开发者_JAVA百科) "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.

0

精彩评论

暂无评论...
验证码 换一张
取 消