简体   繁体   English

如何在Ruby on Rails中使用包含的数据实现REST API?

[英]How to implement a REST API with included data in Ruby on Rails?

I'm working on a Ruby on Rails app which has a REST API. 我正在使用具有REST API的Ruby on Rails应用程序。 I manage two formats JSON and XML. 我管理两种格式的JSON和XML。 Very often to simplify the use if the API, I'm making includes. 如果要编写API,通常会简化使用。 But when you add params to to_json and to_xml like :only, :except, it's not only applied on the root object but on all the objects included. 但是,当您像:only,:except这样将参数添加到to_json和to_xml时,它不仅适用于根对象,而且适用于所有包含的对象。

Do you know libs or methods to answer to these different problems: 您是否知道用于解决这些不同问题的库或方法:

  • Tell never return a user password in the API 告诉永不在API中返回用户密码
  • Tell always include a relationship or a method in each user serialized in the API 告诉总是在API中序列化的每个用户中包含一个关系或一个方法
  • Serialize objects depending on context. 根据上下文序列化对象。 For exemple, when a user ask for the user list, he should see its complete profile, a partial profile of its friends and just the name of others... 例如,当用户要求用户列表时,他应该看到其完整的个人资料,部分朋友的个人资料以及其他人的名字...
  • Don't have to copy paste the parameters for xml and json 不必复制粘贴xml和json的参数

Thank you very much, 非常感谢你,

Camille Roux 卡米尔·鲁(Camille Roux)

You're likely going to want to override the to_xml and to_json methods in each model and ensure that your controller is calling those methods on your objects when returning JSON/XML. 您可能要覆盖每个模型中的to_xmlto_json方法,并确保您的控制器在返回JSON / XML时在对象上调用这些方法。

See http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001876 and http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001873 for the default implementation of these methods. 有关这些方法的默认实现,请参见http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001876http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001873

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

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