开发者

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. I manage two formats JSON and XML. Very often to simplify the use if the API, I'm making includes. 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.

Do you know libs or methods to answer to these different problems:

  • Tell never return a user password in the API
  • Tell always include a relationship or a method in each user serialized in the API
  • Serialize objects depending on context. For exemple, when a us开发者_开发问答er 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

Thank you very much,

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜