Question

Is it possible to conditionally include a has_one association in an active model serializer on a record-by-record basis?

In my case I need to not return an association called "group" if the group is of the type "invisible". Here is a snippet from my serializer.

class PostFeedSerializer < ActiveModel::Serializer
  attributes :id, :title, :thumbnail_photo, :view_count, :ago, :created_by
  has_one :group, serializer: GroupSerializer

What I'd like to do is something to the effect of:

has_one :group, serializer: GroupTinySerializer unless object.get_group.invisible?
Was it helpful?

Solution

Assuming you're using version ~> 0.8.0, you should be able to put the following in your PostFeedSerializer.

def include_group?
  !object.get_group.invisible?
end

That will conditionally include the group object whenever include_group? returns true.

Looks like in future versions, AMS will be moving to filter instead of include_x? methods.

OTHER TIPS

For anyone using a more recent version of Active Model Serializer, the solution would be:

  def filter(keys)
    keys.delete :group unless !object.get_group.invisible?
    keys
  end

You can also do:

has_one :group, serializer: GroupTinySerializer, unless: -> { invisible? }

def invisible?
  object.get_group.invisible?
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top