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"
}
}
有没有办法做到这一点?
Is there some way to do this?
这是我的相关控制器方法:
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屋!