1

每辆车都有关联_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"}]}]
4

2 回答 2

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
于 2012-07-04T22:51:08.460 回答
0
comments = Comment.join(:car).merge(Car.most_recent(params[:how_recent]))

如果你想要自定义 json 输出使用rabl gem

于 2012-07-04T22:50:26.013 回答