我有一个限制在活动模型资源中序列化的关联级别的问题.
例如:
游戏有很多球员有很多玩家
- 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
可能不是最干净的解决方案,但它对我来说很好!