每个汽车都有has_many :comments
关联
我有以下方法来归还我的车:
class Api::V1::CarsController < Api::V1::BaseController
def recent
recent = Car.most_recent(params[:how_recent])
comments = recent.each{|r| r.comments} ## ??
respond_with(:recent => 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"}]}]
答案 0 :(得分: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
答案 1 :(得分:0)
comments = Comment.join(:car).merge(Car.most_recent(params[:how_recent]))
如果你想要自定义json输出使用rabl gem