0
0
RailsHow-ToBeginner · 3 min read

How to Render JSON in Rails: Simple Guide with Examples

In Rails, you render JSON by using render json: object inside a controller action. This converts the Ruby object into JSON format and sends it as the HTTP response.
📐

Syntax

The basic syntax to render JSON in Rails is render json: object. Here, object can be any Ruby object like a hash, array, or ActiveRecord model. Rails automatically converts it to JSON format.

You can also customize the JSON output by passing options like only, except, or methods to control which attributes are included.

ruby
render json: @user

# or with options
render json: @user, only: [:id, :name]
render json: @user, except: [:created_at, :updated_at]
💻

Example

This example shows a Rails controller action that fetches a user and renders it as JSON. The JSON response includes only the user's id and name.

ruby
class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    render json: @user, only: [:id, :name]
  end
end
Output
{"id":1,"name":"Alice"}
⚠️

Common Pitfalls

  • Forgetting to set render json: and instead using render @user which renders a template, not JSON.
  • Trying to render complex objects without serialization, which can cause errors or expose sensitive data.
  • Not handling cases where the object is nil, which can cause unexpected JSON responses.

Always ensure you control which attributes are exposed in JSON to avoid leaking sensitive information.

ruby
class UsersController < ApplicationController
  def show
    @user = User.find_by(id: params[:id])
    if @user
      render json: @user
    else
      render json: { error: "User not found" }, status: :not_found
    end
  end
end
Output
{"error":"User not found"}
📊

Quick Reference

Here is a quick summary of common render json: options:

OptionDescriptionExample
json:The Ruby object to convert to JSONrender json: @user
only:Include only specified attributesrender json: @user, only: [:id, :name]
except:Exclude specified attributesrender json: @user, except: [:password_digest]
methods:Include custom methods in JSONrender json: @user, methods: [:full_name]
status:Set HTTP status coderender json: { error: 'Not found' }, status: :not_found

Key Takeaways

Use render json: object in controller actions to send JSON responses.
Control JSON output with only, except, and methods options to avoid exposing sensitive data.
Always handle cases where the object might be nil to return meaningful error JSON.
Use HTTP status codes with status: to indicate success or errors in JSON responses.