Something like this should do the trick:

class Api::V1::BookSerializer < ActiveModel::Serializer
  attributes :id, :status, :name, :author_name, :published_date

  attribute :conditional_attribute, if: :some_condition?
  belongs_to :conditional_association, if: :some_other_condition?


  def some_condition?
    # some condition

  def some_other_condition?
    # some other condition

You can also use :unless for negated conditions.

You can use instance_options or instance_reflections in your conditions if you need them (see or you can use scopes (see

Note: To the best of my knowledge, this only works with attribute and association methods – it doesn’t work with attributes (see since it doesn’t pass options along.

I read your comment regarding sticking with AM Serializers, but I’ll still point it out: If you’re looking for a more robust and flexible solution than AM Serializers, jsonapi-serializer or Blueprinter work quite well and both have support for conditional fields as well as conditional associations.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top