2017-10-03 8 views
0

저는 Rails에 비교적 익숙하며 라우팅에 대해 많이 알지 못합니다. 특정 오류 코드 (404)가 표시되면 특정보기 (예 : 404.html.erb)를 표시하려면 어떻게해야합니까? 예를 들어, 사용자가 존재하지 않는 페이지를 얻는 경우 (404), 어떻게들을 수 있고 해당 이벤트의 특정 페이지를 표시 할 수 있습니까?

Rails 앱에 public 폴더가 있고 404, 500 및 422 오류 코드 .html 페이지가 사전 생성되었지만 나에게 적합하지 않은 것으로 알고 있습니다. 존재하지 않는 페이지로 이동하면 GET 오류가 발생합니다. 어떻게 바꿀 수 있니?

감사합니다.레일 : 특정 상태 코드로 페이지를 표시하려면 어떻게해야합니까?

답변

1

사용자 정의 경로를 설정하여 일반 컨트롤러보기 템플릿처럼 컨트롤러의 동적 페이지를 렌더링 할 수 있습니다.

설정/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 

응용 프로그램

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

응용 프로그램/뷰/오류/컨트롤러/errors_controller.rb/

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> 
0

로컬 호스트를 통해 공용 페이지에 액세스 할 수 있습니다. Rails는 오류가 발생하거나 404 프로덕션 환경에서이 페이지를 자동으로 사용합니다. 당신은 다음과 같이 할 수

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

: 이러한 변경 후

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