Search code examples
ruby-on-rails-3ruby-on-rails-4active-model-serializers

Active Model Serializer Conditional Associations


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?

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.