1

当发生路由错误时,如何编写控制器、路由或视图以呈现 404?

例如,如果用户访问一个 url 地址

http://0.0.0.0:3000/posts/likes

likes路径不是路由中的方法。如何将其重定向到 404 页面?

4

3 回答 3

3

快速谷歌搜索提供的资源很少。我建议以下两个。

虽然我个人没有使用过这些,但我认为 gem 可以为您提供强大的帮助。是的,第二个链接来自现实生活场景。

于 2012-10-01T06:23:54.533 回答
2

1.在application_controller.rb中

# ..
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

private
def record_not_found(e)
  render ‘errors/not_found’, :status => 404
end

2.创建一个errors文件夹和一个名为not_found.html.erb的文件

3.将源添加到application_controller.rb

def record_not_found(e)
  render ‘errors/not_found’, :status => 404, :layout => ‘error’
end
于 2012-10-01T06:24:13.967 回答
2

Rails 允许您定义自己的“异常应用程序”来处理错误。这是处理错误的一种方法。在application.rb

config.exceptions_app = self.routes

然后在您的路线中:

match '/404', to: 'errors#not_found'
match '/500', to: 'errors#error'

然后你只需要一个ErrorsControllerwith 方法来处理你想要处理的不同错误,以及每个错误的模板文件,errors.html.erb如果你想使用它,还需要一个布局文件。

ActionController::RoutingErrorActiveRecord::RecordNotFound在生产中自动引发 404。

于 2012-10-01T06:32:14.157 回答