尝试使用带有 gon gem 的 jbuilder 将一个对象及其子对象传递给 javascript,其中对象是一个 lender
并且它有很多子对象,它们是 inventories
。按照 gon gem here 的说明进行操作,但我坚持认为这是 jbuilder 方面的问题,而不是 gon...你会明白为什么的。
获取贷方的当前代码:
#/test.json.builder
json.lenders @lenders, :email, :latitude, :longitude
Controller 代码中的测试操作
@lenders = Signups.all
gon.jbuilder
#/test.html.erb
<script>
console.log(gon.lenders)
</script>
这工作正常,并产生以下输出:
但是,当我尝试根据 Ryan Bates 的节目 notes 使用标准 jbuilder 代码获取子级 inventories
时,像这样:
#/test.json.builder
json.lenders @lenders, :email, :latitude, :longitude
json.inventories @lenders.inventories, :id, :itemlist_id, :description
我收到错误:undefined method
inventories' for #`
我明白为什么会出现错误,因为根据上面的输出,@lenders
的结果是 lenders
的数组,而不是贷方对象本身,但我还能如何获得库存?我期望的目标是输出如上所示,但对于每个对象,都有一个生成数组的 inventories
字段单个 inventory
对象,每个对象都具有属性 id
、itemlist_id
和 description
。
我尝试过的事情产生了同样的错误:
一个 瑞恩·贝茨 (Ryan Bates) 对 child 的另一种变体
json.comments @article.comments do |json, comment|
json.partial! comment
end
#in partial
json.(comment, :id, :name, :content)
两个包括 Controller 代码中的 list
Controller 代码中的测试操作
@lenders = Signups.all.includes(:inventories)
gon.jbuilder
这不是 gon 问题,gon 安装在 gemfile 中的 jbuilder 之后,我将其包含在 View 标题中。
最佳答案
好的,这有效:
#/test.json.builder
json.array!(@lenders) do |json, lender|
json.(lender, :id, :email, :latitude, :longitude)
json.inventories lender.inventories do |json, inventory|
json.(inventory, :id, :itemlist_id, :description)
end
end
关于javascript - 使用jbuilder访问子对象有很多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25456565/