ActiveRecord与嵌套对象与JSON的关系

时间:2012-04-16 12:03:17

标签: ruby json activerecord

我正在使用ActiveRecord和Sinatra。我有AR关系Post has_many Comments

我需要在JSON中创建回复所有帖子及其评论的响应。它应该是这样的:

[
    { 
        "id":1,
        "title:"Title_1",
        "comments":[
            { "content":"lorem ipsum", "post_id":1 },
            { "content":"foo bar",     "post_id":1 },
        ]
    },

    { 
        "id":2,
        "title:"Title_2",
        "comments":[
            { "content":"lorem ipsum", "post_id":2 },
            { "content":"foo bar",     "post_id":2 },
        ]
    }
]

我认为创建这样的响应是一项常见的任务,所以我希望应该有一些很好的方法来实现它。

我的临时解决方案(下面的代码)工作正常,但它太长且不可读:

Post.all.map{|x| x.as_json(include: [:comments]).values[0] }.to_json

这是我找到的另一个解决方案:

Post.all.as_json(include: [:comments]).to_json

可悲的是,返回的结构看起来不同,它将每个帖子包装到其他节点"post: {}"中。我想避免它。

[ 
     { 
          "post":{ 
              "id":1,
              "title:"Title_1",
              "comments":[
                  { "content":"lorem ipsum", "post_id":1 },
                  { "content":"foo bar",     "post_id":1 },
              ]
          }
     },

     { 
          "post":{ 
              "id":1,
              "title:"Title_2",
              "comments":[
                  { "content":"lorem ipsum", "post_id":2 },
                  { "content":"foo bar",     "post_id":2 },
              ]
          }
     }
]

1 个答案:

答案 0 :(得分:2)

尝试:

ActiveRecord::Base.include_root_in_json = false

http://apidock.com/rails/ActiveRecord/Serialization/to_json