加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:46:17 所属栏目:百科 来源:网络整理
导读:我有一个限制在活动模型资源中序列化的关联级别的问题. 例如: 游戏有很多球员有很多玩家 class GameSerializer ActiveModel::Serializer attributes :id has_many :teamsendclass TeamSerializer ActiveModel::Serializer attributes :id 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

当我检索到团队的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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读