Rails: 如何在某个状态码上显示页面?

Rails: How can I display a page on a certain status code?

我是 Rails 的新手,对路由还不是很了解。当用户收到某个错误代码 (404) 时,我将如何显示某个视图(例如 404.html.erb)?例如,如果用户获取了一个不存在的页面 (404),我如何监听该事件并在该事件上显示特定页面?

我知道 Rails 应用程序带有 public 文件夹和预先生成的 404、500 和 422 错误代码 .html 页面,但它们似乎对我不起作用。当我转到一个不存在的页面时,我收到一个 GET 错误。我该如何更改?

谢谢!

您可以通过本地主机访问 public 页面。 Rails 在生产中遇到该错误或 404 时自动使用这些页面。

localhost:3000/404 # => renders the 404.html
localhost:3000/500 # => renders the 500.html

您可以进行以下操作:

# 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'

您可以设置自定义路由以从您的控制器呈现动态页面,就像普通的控制器视图模板一样。

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>