如何在Rails中使用API返回嵌套注释
has_many :comments
都有has_many :comments
关联
我有以下方法来归还我的车:
class Api::V1::CarsController recent) end end
我最近获得了以下汽车:
curl -X GET http://cars.dev/api/v1/cars/recent -d "token=zzxWkB3SzDP3U1wDsJbY" -d "how_recent=20"
我希望得到这样的回应:
"recent_with_comments":{"recent":[{"type":"ferrari","price":null,"user_id":78,"username":null,"comments":[{"id":1, "comment": "some text"},{"id":2, "comment": "some text 2"}]}]
当渲染为json时,你可以传递一些额外的参数,如http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/所示。
基本示例:
class Api::V1::CarsController < Api::V1::BaseController def recent recent = Car.most_recent(params[:how_recent]) comments = recent.each{|r| r.comments} ## ?? respond_to do |format| format.html format.json { render recent.as_json(:include => :comments) } end end end
comments = Comment.join(:car).merge(Car.most_recent(params[:how_recent]))
如果你想要自定义json输出使用rabl gem