How to return correct HTTP error codes from Ruby on Rails application How to return correct HTTP error codes from Ruby on Rails application ruby ruby

How to return correct HTTP error codes from Ruby on Rails application


When you're just giving a status code and there is no body, a convenient way is

head 403

This method also accepts the symbolic names for status codes, such as

head :forbidden


You should render page with correct status.

render(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false)


According to ActionController::Head docs just use this pattern in actions

  return head([status]) if/unless [some condition here]

Example:

  return head(:gone) if @record.deleted?  return head(:forbidden) unless @user.owns?(@record)

return is used to make sure that no remaining code in the action will be run.