如何返回Rails中使用API​​嵌套评论 [英] How to return nested comments using API in Rails

查看:134
本文介绍了如何返回Rails中使用API​​嵌套评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个的has_many:评论协会

我有以下的方法来回报我的汽车:

 类API :: V1 :: CarsController< API :: V1 :: BaseController
  近期高清
      最近= Car.most_recent(PARAMS [:how_recent])
      评论= {recent.each | R | r.comments} ##?
      respond_with(:最近=>近期)
    结束
  结束

我通过取得最近汽车:

 卷曲-X GET http://cars.dev/api/v1/cars/recent -d令牌= zzxWkB3SzDP3U1wDsJbY-dhow_recent = 20

和我想获得回应这样的:

<$p$p><$c$c>\"recent_with_comments\":{\"recent\":[{\"type\":\"ferrari\",\"price\":null,\"user_id\":78,\"username\":null,\"comments\":[{\"id\":1, 意见:一些文本},{ID:2,评论:一些文本2}]}]


解决方案

在为JSON你可以通过一些额外的PARAMS呈现如图所示的 http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/

基本的例子:

 类API :: V1 :: CarsController&LT; API :: V1 :: BaseController
  近期高清
    最近= Car.most_recent(PARAMS [:how_recent])
    评论= {recent.each | R | r.comments} ##?
    做的respond_to |格式|
      format.html
      format.json {渲染recent.as_json(:包括=&GT;:评论)}
    结束
  结束
结束

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

解决方案

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

这篇关于如何返回Rails中使用API​​嵌套评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆