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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 限制协会级联活动模型序列化程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个限制在活动模型资源中序列化的关联级别的问题.

例如:

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

  1. class GameSerializer < ActiveModel::Serializer
  2. attributes :id
  3. has_many :teams
  4. end
  5.  
  6. class TeamSerializer < ActiveModel::Serializer
  7. attributes :id
  8. has_many :players
  9. end
  10.  
  11. class PlayerSerializer < ActiveModel::Serializer
  12. attributes :id,:name
  13. end

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

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

解决方法

另一个选择是滥用Rails的热心加载来确定要呈现的关联:

在您的轨道控制器:

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

那么在AMS土地:

  1. class PostSerializer < ActiveModel::Serializer
  2. attributes :id,:title
  3. has_many :comments,embed: :id,serializer: CommentSerializer,include: true
  4.  
  5. def include_comments?
  6. # would include because the association is hydrated
  7. object.association(:comments).loaded?
  8. end
  9. end

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

猜你在找的Ruby相关文章