活动模型序列化程序中的限制关联级联 [英] Limiting Associations Cascade in Active Model Serializer
问题描述
我在限制活动模型资源中序列化的关联级别时遇到问题.
I'm having an issue with limiting the level of associations serialized within an active model resource.
例如:
一个游戏有很多团队,有很多玩家
A Game has many Teams which 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
当我为 Team 检索 JSON 时,它根据需要将所有球员都包含在一个子数组中.
When I retrieve the JSON for the Team, it includes all the players in a sub array, as desired.
当我检索游戏的 JSON 时,它包含一个子数组中的所有团队,非常好,但也包含每个团队的所有玩家.这是预期的行为,但是否可以限制关联级别?让 Game 只返回序列化的 Teams 而没有 Players?
When I retrieve the JSON for the Game, it includes all the Teams in a sub array, excellent, but also all the players for each Team. This is the expected behaviour but is it possible to limit the level of associations? Have Game only return the serialized Teams without the Players?
推荐答案
另一种选择是滥用 Rails 的预先加载来确定要呈现哪些关联:
Another option is to abuse Rails' eager loading to determine which associations to render:
在你的 rails 控制器中:
In your rails controller:
def show
@post = Post.includes(:comments).find(params[:id])
render json: @post
end
然后在 AMS 土地上:
then in AMS land:
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
可能不是最干净的解决方案,但它对我来说效果很好!
Probably not the cleanest solution, but it works nicely for me!
这篇关于活动模型序列化程序中的限制关联级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!