Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 786
Dan Avatar asked Apr 30 '14 14:04

Dan


2 Answers

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.

like image 70
Aron Avatar answered Oct 16 '22 12:10

Aron


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
like image 33
FutoRicky Avatar answered Oct 16 '22 12:10

FutoRicky