How to Use Active Model Serializer in Ruby on Rails
Use
ActiveModel::Serializer in Ruby on Rails by creating a serializer class for your model that defines attributes to include in JSON output. Then, render your model or collection with the serializer in your controller to get clean, structured JSON responses.Syntax
Create a serializer class inheriting from ActiveModel::Serializer. Inside, use attributes to list model fields to include in JSON. Optionally, define custom methods for computed fields.
In your controller, render the model or collection with render json: @object, and Rails uses the serializer automatically.
ruby
class UserSerializer < ActiveModel::Serializer attributes :id, :name, :email def name "User: " + object.name end end
Example
This example shows a User model with a serializer that customizes the name attribute. The controller renders JSON using the serializer.
ruby
# app/models/user.rb class User < ApplicationRecord # attributes: id, name, email end # app/serializers/user_serializer.rb class UserSerializer < ActiveModel::Serializer attributes :id, :name, :email def name "User: " + object.name end end # app/controllers/users_controller.rb class UsersController < ApplicationController def show user = User.find(params[:id]) render json: user end end
Output
{
"user": {
"id": 1,
"name": "User: Alice",
"email": "alice@example.com"
}
}
Common Pitfalls
- Not creating a serializer class for your model, so Rails falls back to default JSON rendering.
- Forgetting to list attributes in the serializer, resulting in missing fields in output.
- Using instance variables instead of
objectinside serializer methods. - Rendering JSON without specifying the serializer when multiple serializers exist.
ruby
## Wrong: Missing serializer render json: @user ## Right: Serializer defined and used automatically render json: @user ## Wrong: Using instance variable in serializer class UserSerializer < ActiveModel::Serializer def name "User: " + @user.name # wrong end end ## Right: Use object class UserSerializer < ActiveModel::Serializer def name "User: " + object.name end end
Quick Reference
| Concept | Description |
|---|---|
| Serializer Class | Inherit from ActiveModel::Serializer to define JSON structure |
| attributes | List model fields to include in JSON output |
| Custom Methods | Define methods for computed or formatted fields |
| Rendering | Use render json: @model in controller to apply serializer |
| object | Reference the model instance inside serializer methods |
Key Takeaways
Create a serializer class inheriting from ActiveModel::Serializer for each model you want to format.
List attributes inside the serializer to control what appears in JSON output.
Use the object keyword inside serializer methods to access model data.
Render your model or collection with render json: @object to apply the serializer automatically.
Avoid common mistakes like missing serializers or incorrect instance variable usage.