Rails ActiveModelSerializer, combine two lists of same-type-models into one serialized response, with different names

我怕爱的太早我们不能终老 提交于 2019-12-13 03:42:46

问题


I have a rails api, in which I'm using Active Model Serializers (version 0.10.6) to serializer json responses.

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

In this code, the two lists are @users_created_feature_requests, and @feature_requests_in_tagged_leagues

Thanks!


回答1:


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


来源:https://stackoverflow.com/questions/48104901/rails-activemodelserializer-combine-two-lists-of-same-type-models-into-one-seri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!