A comprehensive guide to HTTP status codes in Ruby on Rails

The :status option provides flexibility in customizing the HTTP status code for a Rails response. By default, Rails generates a response with the appropriate HTTP status code, typically 200 OK for successful requests. However, the :status option allows developers to explicitly set the status code, enabling more granular control over response behavior. This option proves particularly useful when the default status code is not suitable for the response, such as returning a 404 Not Found status code for missing resources.

Key Points:

The status classes are as follows:

Each status class has its own associated status codes. For example, the Informational status class has the status codes 100, 101, and 102.

The Ruby on Rails documentation provides a table that lists all possible status codes according to the status classes. The table also includes a description of each status code.

Some of the most used status code

Code Description Example
200 OK A successful request. For example, a request to retrieve a web page would return a 200 status code.
404 Not Found The requested resource was not found. For example, a request to a URL that does not exist would return a 404 status code.
500 Internal Server Error An unexpected error occurred on the server. For example, a server crash would return a 500 status code.
302 Found The requested resource has been moved to a new location. For example, a request to a web page that has been moved to a new URL would return a 302 status code.
403 Forbidden The user does not have permission to access the requested resource. For example, a request to a web page that is password-protected would return a 403 status code.

Here are examples of how to use some HTTP status codes in Ruby on Rails controllers:

200 OK and 403 Forbidden

1
2
3
4
5
6
7
8
9
class UsersController < ApplicationController
  def show
    if current_user.admin?
      render json: current_user, status: :ok, message: "User is an admin."
    else
      render status: :forbidden, message: "User is not an admin."
    end
  end
end

500 Internal Server Error and 201 Created

1
2
3
4
5
6
7
8
9
10
class UsersController < ApplicationController
  def create
    user = User.new(user_params)
    if user.save
      render json: user, status: :created, message: "User created successfully."
    else
      render status: :internal_server_error, message: "An error occurred while creating the user."
    end
  end
end

302 Found and 404 Not Found

1
2
3
4
5
6
7
8
9
10
class ProductsController < ApplicationController
  def edit
    product = Product.find_by_id(params[:id])
    if product
      render :edit, locals: { product: product }, status: :found, message: "Product found."
    else
      render status: :not_found, message: "Product not found."
    end
  end
end