代码之家  ›  专栏  ›  技术社区  ›  camzillajs101

Rails:如何显示特定状态代码的页面?

  •  0
  • camzillajs101  · 技术社区  · 7 年前

    404.html.erb

    我知道Rails应用程序附带了一个 public 文件夹和预生成的404500和422错误代码。html页面,但它们似乎不适合我。当我转到一个不存在的页面时,我收到一个GET错误。我该如何改变这一点?

    谢谢

    3 回复  |  直到 7 年前
        1
  •  1
  •   sa77    7 年前

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

    MyApp::Application.routes.draw do
      # custom error routes
      match '/404' => 'errors#not_found', :via => :all
      match '/500' => 'errors#internal_error', :via => :all
    end
    

    应用程序/控制器/错误_控制器。rb型

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

    应用程序/视图/错误/未找到。html。erb公司

    <div class="container">
      <div class="align-center">
        <h3>Page not found</h3>
        <%= link_to "Go to homepage", root_path %>
      </div>
    </div>
    
        2
  •  0
  •   pauloancheta    7 年前

    localhost:3000/404 # => renders the 404.html
    localhost:3000/500 # => renders the 500.html
    
        3
  •  0
  •   Tai    7 年前

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