How to return nested comments using API in Rails

好久不见. 提交于 2019-12-24 09:07:59

问题


Each Car has has_many :comments association

I have following method to return my cars:

 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

I get recent cars by:

curl -X GET http://cars.dev/api/v1/cars/recent -d "token=zzxWkB3SzDP3U1wDsJbY" -d "how_recent=20"  

And I would like to get response like that:

"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"}]}]

回答1:


When rendering as json you can pass some additional params as shown http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/

basic example:

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



回答2:


comments = Comment.join(:car).merge(Car.most_recent(params[:how_recent]))

if u want custom json output use rabl gem



来源:https://stackoverflow.com/questions/11335704/how-to-return-nested-comments-using-api-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!