Rails RubyChina 的 RoutingError 处理

evan · 2012年10月31日 · 最后由 huacnlee 回复于 2012年11月01日 · 2260 次阅读

想给项目加个 404 处理,看了下 RubyChina 的代码: application_controller.rb

def render_404
  render_optional_error_file(404)
end

def render_403
  render_optional_error_file(403)
end

def render_optional_error_file(status_code)
  status = status_code.to_s
  if ["404","403", "422", "500"].include?(status)
    render :template => "/errors/#{status}", :format => [:html], :handler => [:erb], :status => status, :layout => "application"
  else
    render :template => "/errors/unknown", :format => [:html], :handler => [:erb], :status => status, :layout => "application"
  end
end

加上了似乎也不起作用,错误 url 根本就没进 application_controller.rb 似乎跟 routes.rb 有关系,似乎又跟 require 'api'有关系,求指教~ 我用的是 rails3.0

routes.rb 最底下加上一句 match "*a", :to => "errors#routing" 然后创建一个 controller

class ErrorsController < ApplicationController

  def routing
    respond_to do |format|
      format.html { render :error_404 }
      format.all { render nothing: true, status: 404  }
    end

  end
end

render_404 应该是从具体 controller 里边的方法调用的,你确认一下

render_404 这个方法我是用在一些需要强制显示 404 的场景

需要 登录 后方可回复, 如果你还没有账号请 注册新账号