[英]Active model serializer each_serializer vs serializer
I have noticed when I want to fetch the collection of objects (@user.all) I have to user each_serializer我注意到当我想获取对象集合 (@user.all) 时,我必须使用 each_serializer
render json: @users, root: 'data', each_serializer: User::ShowSerializer
whereas when I have to have a single object show action serializer works.而当我必须有一个对象时,显示动作序列化程序可以工作。
render json: @user, root: 'data', serializer: User::ShowSerializer
Please can anyone explain the difference between the two请任何人都可以解释两者之间的区别
Think of it as the each
iterator in Ruby.将其视为 Ruby 中的
each
迭代器。
When you have a single record @user
, no iteration is required, and in return you get a single serialized resource.当您只有一条记录
@user
,不需要迭代,作为回报,您将获得一个序列化资源。 Here we directly apply a serializer
:这里我们直接应用一个
serializer
:
render json: @user, root: 'data', serializer: User::ShowSerializer
Think of this as the same as认为这与
User::ShowSerializer(@user)
When you have a collection of records, such as @user.all
, you have to iterate over each resource to get a serialized collection of records.当您有一个记录集合(例如
@user.all
,您必须遍历每个资源以获取序列化的记录集合。 Here we apply each_serializer
:这里我们应用
each_serializer
:
render json: @users, root: 'data', each_serializer: User::ShowSerializer
This is the same as这与
@users.each do |user|
User::ShowSerializer(user)
end
For a collection对于一个集合
:serializer specifies the collection serializer and :serializer指定集合序列化器和
:each_serializer specifies the serializer for each resource in the collection. :each_serializer为集合中的每个资源指定序列化器。 For a single resource, the :serializer option is the resource serialize
对于单个资源, :serializer 选项是资源序列化
Please take a look at this documentation for more detail请查看此文档以获取更多详细信息
Basically :serializer returns a JSON Object基本上:serializer返回一个 JSON 对象
and :each_serializer returns array of JSON Objects和:each_serializer返回 JSON 对象数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.