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?

  private

  def some_condition?
    # some condition
  end

  def some_other_condition?
    # some other condition
  end
end

You can also use :unless for negated conditions.

You can use instance_options or instance_reflections in your conditions if you need them (see https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/howto/passing_arbitrary_options.md) or you can use scopes (see https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#scope)

Note: To the best of my knowledge, this only works with attribute and association methods – it doesn’t work with attributes (see https://github.com/rails-api/active_model_serializers/blob/0-10-stable/lib/active_model/serializer.rb#L204-L210) 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