Limiting Associations Cascade in Active Model Serializer

限于喜欢 提交于 2019-11-29 21:56:34

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!

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!