2014-02-28 50 views
0

我試圖用RABL生成JSON的子節點,我index.rabl看法是這樣的:生成JSON與Rabl的,使用集合作爲根對象

collection @products => :products 
    attributes :id, :name, :price, :category_id 

node(:total) {@products.count} 

這將生成JSON結構如下:

{"products":[{"id":1,"name":"product name","price":0.00,"category_id":1,"total":30}, 
      {"id":2,"name":"product2 name","price":0.00,"category_id":1,"total":30},...]} 

然而,我想生成的JSON的結構,如下所示:

{ "products":[{"id":1,"name":"product name","price":0.00,"category_id":1}, 
       {"id":2,"name":"product2 name","price":0.00,"category_id":1},...], 
    "total":30 
} 

這意味着我想從"products"數組中取出"total":30並將其放入生成的JSON的根對象中。我需要對我的視圖文件進行哪些更改才能生成所需的JSON?我對RABL的經驗很少,我將非常感謝他們的幫助。

回答

1

在你index.json.rabl,你可以這樣做:

object false 
child @events do 
    attributes :id, :message 
end 
node(:count) { @events.size } 

結果是:

{ 
    "count": 50, 
    "events": [ 
     { 
      "id": 124, 
      "message": "Hola" 
     }, 
     { 
      "id": 123, 
      "message": "Chau" 
     }, 
     { 
      "id": 122, 
      "message": "Yeah baby!" 
     } 
    ] 
} 

我已經在我的項目測試這一點。您可以用產品更改活動...