rails render json only some attributes

To render only specific attributes in JSON using Ruby on Rails, follow these steps:

  1. Define a Serializer for the Model: class PostSerializer < ActiveModel::Serializer attributes :title, :body end

  2. Use the Serializer in Controller: def show post = Post.find(params[:id]) render json: post, serializer: PostSerializer end

  3. Customize Serialization Options: # To include associations class PostSerializer < ActiveModel::Serializer attributes :title, :body has_many :comments end

# To rename attributes class PostSerializer < ActiveModel::Serializer attributes :title attribute :content, key: :body end