簡體   English   中英

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錯誤。 我將如何改變呢?

謝謝!

您可以設置自定義路由,以像常規控制器視圖模板一樣從控制器呈現動態頁面。

配置/ 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

應用程序/控制器/ errors_controller.rb

class ErrorsController < ApplicationController    
  def not_found
    render(:status => 404)
  end
end

應用程序/視圖/錯誤/ 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>

您可以通過本地主機訪問公共頁面。 當遇到錯誤或生產中出現404時,Rails會自動使用這些頁面。

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM