2012-04-16 60 views
1

我使用ActiveRecord與Sinatra。我有AR關係Post has_many CommentsActiveRecord與JSON的嵌套對象的關係

我需要在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 }, 
       ] 
      } 
    } 
] 

回答