【问题标题】:Getting access to :not_found, :internal_server_error etc. in Rails 3在 Rails 3 中访问 :not_found、:internal_server_error 等
【发布时间】:2011-04-04 17:53:30
【问题描述】:

ActionController::StatusCodes 似乎已从 Rails 3 中删除。

我使用了 HTTP 状态代码的同义词,例如

200 => :ok
404 => :not_found
500 => :internal_server_error

更多代码见这里:

http://apidock.com/rails/ActionController/Base/render#254-List-of-status-codes-and-their-symbols

在 Rails 3 中哪里可以找到这些?

【问题讨论】:

    标签: ruby-on-rails-3 actioncontroller


    【解决方案1】:

    Ruby on Rails 使用Rack。状态码定义在 Rack::Utils:

    HTTP_STATUS_CODES = {
      100  => 'Continue',
      101  => 'Switching Protocols',
      102  => 'Processing',
      200  => 'OK',
      201  => 'Created',
      ...
    }
    

    然后这些用于创建符号(即:switching_protocols):

    SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
      [message.downcase.gsub(/\s|-/, '_').to_sym, code]
    }.flatten]
    

    整个代码是browsable here

    【讨论】:

      【解决方案2】:

      似乎错误代码位于action_dispatch/middleware/show_exceptions.rb 中,其中符号映射到实际异常:

        'ActionController::RoutingError'             => :not_found,
        'AbstractController::ActionNotFound'         => :not_found,
        'ActiveRecord::RecordNotFound'               => :not_found,
        'ActiveRecord::StaleObjectError'             => :conflict,
        'ActiveRecord::RecordInvalid'                => :unprocessable_entity,
        'ActiveRecord::RecordNotSaved'               => :unprocessable_entity,
        'ActionController::MethodNotAllowed'         => :method_not_allowed,
        'ActionController::NotImplemented'           => :not_implemented,
        'ActionController::InvalidAuthenticityToken' => :unprocessable_entity
      

      但是 100 - 400 范围的映射从 Rails 中消失了,可能是因为它们是 already present in Rack

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2014-02-14
      相关资源
      最近更新 更多