在Rails 3中访问:not_found,:internal_server_error等

时间:2011-04-04 17:53:31

标签: ruby-on-rails-3 actioncontroller

看起来已经从Rails 3中删除了ActionController::StatusCodes

我使用了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中找到这些?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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