Ruby on rails 3 活动模型序列化程序中的限制关联级联

Ruby on rails 3 活动模型序列化程序中的限制关联级联,ruby-on-rails-3,active-model-serializers,Ruby On Rails 3,Active Model Serializers,我在限制活动模型资源中序列化的关联级别方面遇到了问题 例如: 一场比赛有很多队,其中有很多球员 class GameSerializer < ActiveModel::Serializer attributes :id has_many :teams end class TeamSerializer < ActiveModel::Serializer attributes :id has_many :players end class PlayerSerializ

我在限制活动模型资源中序列化的关联级别方面遇到了问题

例如:

一场比赛有很多队,其中有很多球员

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
class GameSerializer
当我为团队检索JSON时,它根据需要包含子数组中的所有参与者


当我为游戏检索JSON时,它包括子数组中的所有团队,非常好,但也包括每个团队的所有玩家。这是预期的行为,但是否有可能限制关联程度?让游戏只返回序列化的团队而不返回玩家?

您可以创建另一个
序列化程序:

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

  def include_teams?
    @options[:include_teams]
  end
end

另一种选择是滥用Rails的急切加载来确定要呈现的关联:

在rails控制器中:

def show
  @post = Post.includes(:comments).find(params[:id])
  render json: @post
end
然后在AMS土地:

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
class PostSerializer

可能不是最干净的解决方案,但对我来说效果很好

谢谢Pablo,这就是我最后要做的。。。我试着让它有点rails-y,modeling:index和:show多重化,但是有一个
TeamsSerializer
TeamSerializer
。特殊情况下会使用不同的序列化程序。@options从何而来?
object.association(:comments)。已加载?
这正是我想要的,谢谢!我认为这个方法比公认的答案更简洁。从活动的\u模型\u序列化程序文档中,建议在控制器中使用联接或包含来包含关联,以避免n+1查询。在序列化程序中,我遇到了一个难题,那就是如何确定是否加载了关联或忽略了关联。在文档中:“通过确保以最佳方式加载数据来避免n+1查询,例如,如果您使用的是ActiveRecord,您可能需要根据需要使用查询包含或连接”我必须在哪里调用包含注释?方法?
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