ActiveRecord 删除限制错误

5

Page.rb

has_many :comments, :dependent => :restrict

这种验证会引发错误

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

有没有一种方法可以像flash消息或其他验证消息一样显示它?
2个回答

16

使用begin/rescue捕获异常,然后将错误消息添加到页面的基础错误中...我的语法可能有误,但类似于...

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

8

如果您不想在许多控制器中放置begin rescue块,您还可以在应用程序控制器中处理它。

controllers/application_controller.rb

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

它会将请求重定向到来自该请求的页面或资源,并显示弹出消息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接