在Rails中重定向到自定义错误页面

时间:2015-06-10 18:54:59

标签: ruby-on-rails routes

在我的routes.rb中,我有以下内容:

  %w(401 404 422 500 ).each do |code|
    get code, :to => "errors#show", :code => code
  end

根据rake路线创建以下路线:

  GET      /401(.:format)      errors#show {:code=>"401"}
  GET      /404(.:format)      errors#show {:code=>"404"}
  GET      /422(.:format)      errors#show {:code=>"422"}
  GET      /500(.:format)      errors#show {:code=>"500"}

这是我的错误控制器:

class ErrorsController < ApplicationController
    def show
        Rails.logger.debug("ERROR WITH STATUS #{status_code.to_s}")
        render status_code.to_s, :status => status_code
    end

    def unauthorized
        render "401"
    end

    protected

    def status_code
        Rails.logger.debug("STATUS CODE: #{params[:code]}")
        params[:code] || 500
    end
end

在我的观点中,我在&#34;错误&#34;

文件夹下面有以下页面
  • 401.html.erb
  • 404.html.erb
  • 422.html.erb
  • 500.html.erb

我想重定向到控制器中的错误页面。如果我想重定向到401,我该怎么做?

1 个答案:

答案 0 :(得分:0)

我能够通过将此路由添加到我的routes.rb来解决问题:

get "errors/unauthorized"

这会在我的错误控制器中调用“未授权”操作:

def unauthorized
    render "401"
end
相关问题