简体   繁体   English

在Ruby on Rails 4应用程序上自定义JSON结果

[英]Customize JSON Result on a Ruby on Rails 4 application

I'm using a ruby on rails backend for a application I'm working on. 我正在为正在处理的应用程序在Rails后端使用ruby。

I use ActiveModel::Serializer to handle the JSON results of my API: 我使用ActiveModel::Serializer处理我的API的JSON结果:

format.json { render json: data, status: status } 

In some cases I only want to give the user a possibility to query for specific attributes. 在某些情况下,我只希望为用户提供查询特定属性的可能性。

So eg a profile has a rank in a highscore which takes "quite long" to be calculated. 因此,例如,配置文件在高分中的排名需要“相当长”的时间来计算。 So if the user passes in an attribute with: requestedAttributes: [:highscore, :messages] I want to return the highscore and the messages in my rendered JSON response. 因此,如果用户使用以下属性传递属性: requestedAttributes: [:highscore, :messages]我想在渲染的JSON响应中返回高分和消息。 This attributes can change, so writing a Serializer for each listing is not an option! 此属性可以更改,因此不能为每个列表编写序列化程序!

Can anyone help me with that? 有人可以帮我吗?

Thanks a lot! 非常感谢!

You can provide an option hash to as_json in order to specify the desired attributes. 您可以为as_json提供option hash ,以指定所需的属性。

check here ActiveModel::Serializers::JSON 在这里检查ActiveModel :: Serializers :: JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM