目前我的JSON請求返回下面,其中每個人/ lender
有很多inventories
。使用Jbuilder構建一個嵌套的JSON請求
#output of /test.json
[
{"id":13, "email":"[email protected]", "inventories":
[
{"id":10,"name":"2-Person Tent","category":"Camping"},
{"id":11,"name":"Sleeping bag","category":"Camping"},
{"id":27,"name":"6-Person Tent","category":"Camping"}
]
},
{"id":14, "email":"[email protected]", "inventories":
[
{"id":30,"name":"Electric drill","category":"Tools"},
{"id":1,"name":"Hammer","category":"Tools"},
{"id":37,"name":"Plane","category":"Tools"}
]
}
]
我需要再嵌套一件東西,而且這樣做很麻煩。對於上下文,每個inventory
項目通過它的id作爲borrow
記錄中的外鍵引用。每個borrow
記錄屬於存儲returndate
和pickupdate
的父母request
。我現在需要的是每個inventory
項目,以嵌套所有request
記錄的陣列,其中包含關於pickupdate
和returndate
的信息。換句話說,所需的輸出:
[
{"id":13, "email":"[email protected]", "inventories":
[
{"id":10,"name":"2-Person Tent","category":"Camping", "requests":
[
{"id":1, "pickupdate":"2014-07-07","returndate":"2014-07-10"},
{"id":2, "pickupdate":"2014-06-02","returndate":"2014-06-05"},
{"id":3, "pickupdate":"2014-08-14","returndate":"2014-08-20"}
]
},
{"id":11,"name":"Sleeping bag","category":"Camping", "requests":
[
{"id":4, "pickupdate":"2014-05-27","returndate":"2014-05-30"},
{"id":5, "pickupdate":"2014-04-22","returndate":"2014-04-25"}
]
},
{"id":27,"name":"6-Person Tent","category":"Camping", "requests":
[
{"id":6, "pickupdate":"2014-07-10","returndate":"2014-07-12"}
]
}
]
},
{"id":14, "email":"[email protected]", "inventories":
...
我寫了下面的代碼:
json.array!(@lenders) do |json, lender|
json.(lender, :id, :email)
json.inventories lender.inventories do |json, inventory|
json.id inventory.id
json.name Itemlist.find_by_id(inventory.itemlist_id).name
#code below says, json.requests should equal all the Requests where there is a Borrows within that Request that is using the Inventory in question
json.requests Request.select { |r| r.borrows.select { |b| b.inventory_id == inventory.id }.present? } do |json, request|
json.pickupdate request.pickupdate
json.returndate request.returndate
end
end
end
當我刷新頁面,我得到wrong number of arguments (0 for 2..5)
我覺得這個問題是,Request.select...
正在返回一個數組,這不是什麼需要去這裏......但在早先的嵌套函數lender.inventories
是一個Inventory::ActiveRecord_Associations_CollectionProxy
,但我不知道如何解決這個問題。
注:有人說,問題可能是不像inventories
和lender
之間的嵌套,有沒有inventory
和request
之間的明確聯繫,但再行json.name Itemlist.find_by_id(inventory.itemlist_id).name
工作,所以我不知道這是正確的。 (如果是這種情況,我不知道如何繞過這個限制...我目前不想在兩者之間建立關係。)
謝謝!