How to Use Serializer in Rails for JSON Responses
In Rails, use
ActiveModel::Serializer to define how your models are converted to JSON. Create a serializer class for your model, specify attributes to include, and then render JSON using that serializer in your controller.Syntax
To use a serializer in Rails, create a serializer class inheriting from ActiveModel::Serializer. Inside, list the model attributes you want to include in the JSON output using attributes. Then, in your controller, render the model or collection with serializer: YourSerializer.
This separates data formatting from your controller logic, making your API responses clean and consistent.
ruby
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email
end
# In controller
render json: @user, serializer: UserSerializerExample
This example shows a simple UserSerializer that includes id, name, and email. The controller renders a user as JSON using this serializer.
ruby
class UserSerializer < ActiveModel::Serializer attributes :id, :name, :email end class UsersController < ApplicationController def show user = User.find(params[:id]) render json: user, serializer: UserSerializer end end
Output
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
Common Pitfalls
- Forgetting to specify
attributesin the serializer results in empty JSON objects. - Not installing the
active_model_serializersgem or not restarting the server after adding it. - Rendering JSON without specifying the serializer when multiple serializers exist can cause unexpected output.
- Trying to serialize associations without defining them in the serializer.
ruby
class UserSerializer < ActiveModel::Serializer # Missing attributes declaration end # Wrong usage in controller render json: @user # Correct usage class UserSerializer < ActiveModel::Serializer attributes :id, :name end render json: @user, serializer: UserSerializer
Quick Reference
Use this quick guide to remember key steps:
- Create serializer:
rails g serializer ModelName - Define
attributesin serializer - Render JSON in controller with
render json: @model, serializer: ModelNameSerializer - For associations, use
has_manyorhas_onein serializer
Key Takeaways
Create a serializer class inheriting from ActiveModel::Serializer to format JSON output.
List model attributes inside the serializer using the attributes method.
Render JSON in controllers specifying the serializer to control output.
Always restart your Rails server after adding or changing serializers.
Define associations in serializers to include related data properly.