目前我的JSON请求返回以下内容,其中每个人/ lender
都有很多inventories
。
#output of /test.json
[
{"id":13, "email":"johndoe@example.com", "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":"janedoe@example.com", "inventories":
[
{"id":30,"name":"Electric drill","category":"Tools"},
{"id":1,"name":"Hammer","category":"Tools"},
{"id":37,"name":"Plane","category":"Tools"}
]
}
]
我需要再嵌套一件事,而且我很难这样做。对于上下文,每个inventory
项通过它的id作为borrow
记录中的外键引用。每个borrow
记录属于request
父级,用于存储returndate
和pickupdate
。我现在需要的是,为每个inventory
项目嵌套所有request
条记录的数组,并提供有关pickupdate
和returndate
的信息。换句话说,期望的输出:
[
{"id":13, "email":"johndoe@example.com", "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":"janedoe@example.com", "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
行有效,所以我不确定这是对的。 (如果是这种情况,我不确定如何绕过这个限制......我现在不想在两者之间建立关系。)
谢谢!
答案 0 :(得分:0)
ARG。好的,所以这段代码是完全正确的。问题在于我将Gon gem与Jbuilder结合使用,而Request是Gon中的预定义类。
所以只需将代码更改为
@requestrecords.select....
在控制器中:
@requestrecords = Request.all
-__-