Rails ActiveModelSerializer,将两个相同类型模型的列表组合成一个序列化的响应,并使用不同的名称 [英] Rails ActiveModelSerializer, combine two lists of same-type-models into one serialized response, with different names
问题描述
我有一个rails api,在其中我使用Active Model Serializers(版本0.10.6)来序列化json响应.
I have a rails api, in which I'm using Active Model Serializers (version 0.10.6) to serializer json responses.
我有两个数组,它们的端点类型均为"FeatureRequest",该数组返回用户发出的请求列表以及标记了用户的第二个请求列表.理想情况下,我想序列化响应看起来像这样:
I have two arrays, both are of type "FeatureRequest" in an endpoint that returns a list of requests a user has made, and a second list of requests that a user is tagged in. Ideally, I'd like to serialize the response to look something like this:
{
"my_requests" : {
...each serialized request...
},
"tagged_requests" : {
...each serialized request, using the same serializer"
}
}
有什么办法吗?
这是我相关的控制器方法:
Here's my relevant controller method:
def index_for_user
user = User.includes(leagues: :feature_requests).find(params[:user_id])
# Find all requests that this user created
@users_created_feature_requests = FeatureRequest.requests_for_user(user.id)
@feature_requests_in_tagged_leagues = []
user.leagues.each do |league|
@feature_requests_in_tagged_leagues << league.feature_requests
end
...some serialized response here
end
在此代码中,两个列表是@users_created_feature_requests和@feature_requests_in_tagged_leagues
In this code, the two lists are @users_created_feature_requests, and @feature_requests_in_tagged_leagues
谢谢!
推荐答案
假设您有一个像FeatureRequestSerializer
这样的序列化器,则可以通过以下方式实现:
Assuming you have a serializer like FeatureRequestSerializer
, you can achieve that in the following way:
def index_for_user
user = ...
users_created_feature_requests = ...
feature_requests_in_tagged_leagues = user.leagues.map(&:feature_requests)
# serialized response
render json: {
my_requests: serialized_resource(users_created_feature_requests)
tagged_requests: serialized_resource(feature_requests_in_tagged_leagues)
}
end
private
def serialized_resource(collection, adapter = :attributes)
ActiveModelSerializers::SerializableResource.new(collection,
each_serializer: FeatureRequestSerializer,
adapter: adapter
).as_json
end
这篇关于Rails ActiveModelSerializer,将两个相同类型模型的列表组合成一个序列化的响应,并使用不同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!