ruby-on-rails-3 – 限制协会级联活动模型序列化程序

我有一个限制在活动模型资源中序列化的关联级别的问题.

例如:

游戏有很多球员有很多玩家

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

当我检索到团队的JSON,它包括所有的子数组中的玩家,根据需要.

当我检索到游戏的JSON时,它包括了所有团队在一个子阵列,优秀,但也是所有的球员为每个队.这是预期的行为,但是是否可以限制关联水平?游戏只返回序列化的队伍,没有玩家?

解决方法

一个选择是滥用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

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...