【问题标题】:Rails: How can I display a page on a certain status code?Rails:如何在某个状态码上显示页面?
【发布时间】:2017-10-03 00:14:29
【问题描述】:
我对 Rails 比较陌生,对路由还不是很了解。当用户收到某个错误代码 (404) 时,我将如何显示某个视图(例如 404.html.erb)?例如,如果用户 GET 到一个不存在的页面 (404),我如何监听该页面并在该事件中显示某个页面?
我知道 Rails 应用程序带有 public 文件夹和预生成的 404、500 和 422 错误代码 .html 页面,但它们似乎对我不起作用。当我转到一个不存在的页面时,我收到一个 GET 错误。我该如何改变呢?
谢谢!
【问题讨论】:
标签:
ruby-on-rails
url-routing
【解决方案1】:
您可以设置自定义路由以从控制器呈现动态页面,就像普通的控制器视图模板一样。
config/routes.rb
MyApp::Application.routes.draw do
# custom error routes
match '/404' => 'errors#not_found', :via => :all
match '/500' => 'errors#internal_error', :via => :all
end
app/controllers/errors_controller.rb
class ErrorsController < ApplicationController
def not_found
render(:status => 404)
end
end
app/views/errors/not_found.html.erb
<div class="container">
<div class="align-center">
<h3>Page not found</h3>
<%= link_to "Go to homepage", root_path %>
</div>
</div>
【解决方案2】:
您可以通过 localhost 访问公共页面。 Rails 在生产环境中遇到该错误或 404 时会自动使用这些页面。
localhost:3000/404 # => renders the 404.html
localhost:3000/500 # => renders the 500.html
【解决方案3】:
你可以这样做:
# in config/application.rb
config.exceptions_app = self.routes
# For testing on development environment, need to change consider_all_requests_local
# in config/development.rb
config.consider_all_requests_local = false
这些更改后重新启动服务器。
# in routes.rb
get '/404', to: 'errors#not-found'
get '/422', to: 'errors#unprocessable-entity'
get '/500', to: 'errors#internal-error'