ruby 27 lines · 2 tabs

Serializers with ActiveModel::Serializers

Alex Kumar Jan 2026
2 tabs
class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :excerpt, :body, :published_at, :views, :likes_count, :comments_count

  attribute :can_edit, if: :current_user_can_edit?

  belongs_to :author, serializer: UserSummarySerializer
  has_many :comments, if: :include_comments?

  def excerpt
    object.body&.truncate(200)
  end

  def current_user_can_edit?
    scope && (scope.id == object.author_id || scope.admin?)
  end

  def include_comments?
    instance_options[:include_comments] == true
  end
end
2 files · ruby Explain with highlit

Controllers shouldn't know about JSON structure—that's a serialization concern. ActiveModel::Serializers (AMS) separates presentation from business logic by defining dedicated serializer classes for each model. Serializers specify exactly which attributes to expose and handle nested associations cleanly. I can create different serializers for different contexts (list view vs detail view) without cluttering controllers. The if: option conditionally includes fields based on permissions or feature flags. AMS also supports meta attributes and links for JSONAPI-compliant responses. For high-performance APIs, I sometimes use simpler solutions like Jbuilder or custom PORO serializers, but AMS provides good defaults with minimal boilerplate for standard REST APIs.


Related snips

Share this code

Here's the card — post it anywhere.

Serializers with ActiveModel::Serializers — share card
Link copied