0
0
Ruby on Railsframework~5 mins

JSON rendering in Ruby on Rails

Choose your learning style9 modes available
Introduction

JSON rendering lets your Rails app send data in a simple format that other apps or websites can easily understand.

When building an API to share data with mobile apps.
When your web page needs to get data from the server without reloading.
When you want to send structured data to JavaScript on the client side.
When integrating with third-party services that expect JSON data.
Syntax
Ruby on Rails
render json: object_or_hash

You use render json: inside controller actions to send JSON responses.

The object you pass can be a Ruby hash, array, or ActiveRecord model.

Examples
Sends a simple JSON object with a message.
Ruby on Rails
render json: { message: "Hello, world!" }
Sends the JSON representation of a user record.
Ruby on Rails
render json: @user
Sends JSON for multiple users but only includes id and name fields.
Ruby on Rails
render json: @users.to_json(only: [:id, :name])
Sample Program

This controller action sends a JSON response with a greeting and the current time.

Ruby on Rails
class GreetingsController < ApplicationController
  def hello
    render json: { greeting: "Hi there!", time: Time.now }
  end
end
OutputSuccess
Important Notes

JSON keys are usually strings in the output, even if you use symbols in Ruby.

You can customize JSON output using to_json options or serializers.

Remember to set correct headers; Rails does this automatically with render json:.

Summary

Use render json: in Rails controllers to send data as JSON.

This helps your app communicate with other apps or JavaScript easily.

You can control what data is included in the JSON response.