Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Associations Cascade in Active Model Serializer

I'm having an issue with limiting the level of associations serialized within an active model resource.

For example:

A Game has many Teams which has many Players

class GameSerializer < ActiveModel::Serializer
  attributes :id
  has_many :teams
end

class TeamSerializer < ActiveModel::Serializer
  attributes :id
  has_many :players
end

class PlayerSerializer < ActiveModel::Serializer
  attributes :id, :name
end

When I retrieve the JSON for the Team, it includes all the players in a sub array, as desired.

When I retrieve the JSON for the Game, it includes all the Teams in a sub array, excellent, but also all the players for each Team. This is the expected behaviour but is it possible to limit the level of associations? Have Game only return the serialized Teams without the Players?

like image 200
Greg Olsen Avatar asked May 01 '13 02:05

Greg Olsen


2 Answers

Another option is to abuse Rails' eager loading to determine which associations to render:

In your rails controller:

def show
  @post = Post.includes(:comments).find(params[:id])
  render json: @post
end

then in AMS land:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title
  has_many :comments, embed: :id, serializer: CommentSerializer, include: true

  def include_comments?
    # would include because the association is hydrated
    object.association(:comments).loaded?
  end
end

Probably not the cleanest solution, but it works nicely for me!

like image 173
Kieran Huggins Avatar answered Dec 17 '22 11:12

Kieran Huggins


You can create another Serializer:

class ShortTeamSerializer < ActiveModel::Serializer
  attributes :id
end

Then:

class GameSerializer < ActiveModel::Serializer
  attributes :id
  has_many :teams, serializer: ShortTeamSerializer
end

Or you can define a include_teams? in GameSerializer:

class GameSerializer < ActiveModel::Serializer
  attributes :id
  has_many :teams

  def include_teams?
    @options[:include_teams]
  end
end
like image 38
Pablo B. Avatar answered Dec 17 '22 13:12

Pablo B.