当使用不存在的 id 访问对象的显示页面时,会抛出 RecordNotFonud
异常。有没有办法可以重定向到某个错误页面,或者在抛出此错误时可能采取不同的操作?
最佳答案
如果您使用 Rails 3,则可以使用 rescue_from:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
def render_404
respond_to do |format|
format.html { render :action => "errors/404.html.erb", :status => 404 }
# and so on..
end
end
end
是的,您也可以进行重定向而不是渲染,但这不是一个好主意。任何与您站点的半自动交互都会认为传输成功(因为返回的代码不是 404),但收到的资源不是您的客户想要的资源。
关于ruby-on-rails - Ruby on Rails : How do I change the behavior of RecordNotFound?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7244075/