[英]Rails: How can I display a page on a certain status code?
I'm relatively new to Rails, and I still don't know a lot about routing. 我对Rails比较陌生,但是对路由我还是不太了解。 How would I display a certain view (such as
404.html.erb
) when the user gets a certain error code (404)? 当用户收到某个错误代码(404)时,如何显示某个视图(例如
404.html.erb
)? For example, if a user GETs a page that doesn't exist (404), how can I listen for that and display a certain page on that event? 例如,如果用户获取一个不存在的页面(404),我该如何监听该事件并在该事件上显示某个页面?
I know that a Rails app comes with a public
folder and pre-generated 404, 500, and 422 error code .html pages, but they don't seem to work for me. 我知道,一个Rails应用程序带有一个
public
文件夹,并预先生成404,500,和422错误代码的.html页面,但他们似乎并没有为我工作。 When I go to a page that doesn't exist, I receive a GET error. 当我转到一个不存在的页面时,我收到一个GET错误。 How would I change this?
我将如何改变呢?
Thanks! 谢谢!
You can setup custom routes to render dynamic pages from your controller just as normal controller-view templates. 您可以设置自定义路由,以像常规控制器视图模板一样从控制器呈现动态页面。
config/routes.rb 配置/ 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 应用程序/控制器/ errors_controller.rb
class ErrorsController < ApplicationController
def not_found
render(:status => 404)
end
end
app/views/errors/not_found.html.erb 应用程序/视图/错误/ 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>
You can access the public pages through the localhost. 您可以通过本地主机访问公共页面。 Rails automatically uses those pages when it encounters that error or 404 on production.
当遇到错误或生产中出现404时,Rails会自动使用这些页面。
localhost:3000/404 # => renders the 404.html
localhost:3000/500 # => renders the 500.html
You can do as below: 您可以执行以下操作:
# 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
Restart server after those changes. 这些更改后,请重新启动服务器。
# in routes.rb
get '/404', to: 'errors#not-found'
get '/422', to: 'errors#unprocessable-entity'
get '/500', to: 'errors#internal-error'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.