在JBuilder中生成嵌套的JSON数组 [英] Generate a nested JSON array in JBuilder
本文介绍了在JBuilder中生成嵌套的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个模型在红宝石的轨道上
I have this models in ruby on rails
分支模型:has_many:menus
Branch model: has_many :menus
class Branch < ActiveRecord::Base
belongs_to :place
belongs_to :city
has_many :menus , dependent: :destroy
belongs_to :type_place
end
菜单模型:has_many:products
Menu model: has_many :products
class Menu < ActiveRecord::Base
attr_accessible :description, :product_name, :price, :category_id, :menu_id
belongs_to :branch
has_many :products, dependent: :destroy
end
产品型号:
class Product < ActiveRecord::Base
belongs_to :menu
belongs_to :category
end
在视图中具有以下代码:
with the following code in the view:
if @condition
json.code :success
json.branch do
json.array!(@branches) do |json, branch|
json.(branch, :id, :branch_name, :barcode)
json.menu branch.menus, :id, :menu_name
end
end
else
json.code :error
json.message 'Mensaje de error'
end
获取:
{
"code": "success",
"branch": [
{
"id": 1,
"branch_name": "Sucursal 1",
"barcode": "zPOuByzEFe",
"menu": [
{
"id": 2,
"menu_name": "carta sucursal 1"
}
]
},
{
"id": 2,
"branch_name": "Sucursal Viña Centro",
"barcode": "RlwXjAVtfx",
"menu": [
{
"id": 1,
"menu_name": "carta viña centro"
},
{
"id": 5,
"menu_name": "carta viña centro vinos"
}
]
},
{
"id": 3,
"branch_name": "dddd",
"barcode": "eSbJqLbsyP",
"menu": [
]
}
]
}
但是,当我得到每个菜单的产品吗?,我怀疑需要迭代菜单,但是我尝试了几种方法,但均未成功.
But as I get the products of each menu?, I suspect I need to iterate menu, but I have tried several ways without success.
推荐答案
我不确定您的产品可以拥有哪些属性,但我会尝试以下方法:
I'm not sure which attributes your product can have but i would try something like:
if @condition
json.code :success
json.array!(@branches) do |json, branch|
json.(branch, :id, :branch_name, :barcode)
json.menus branch.menus do |json,menue|
json.id menue.id
json.menu_name menue.menu_name
json.products menue.products do |json, product|
json.product_attribute_1 product.product_attribute_1
end
end
end
else
json.code :error
json.message 'Mensaje de error'
end
我也不太确定为什么要尝试将@branches嵌套在如下所述的分支下:
i'm also not quite sure why you try to nest @branches under a branch as stated by:
json.branch do
...
end
我刚刚删除了那个.
这篇关于在JBuilder中生成嵌套的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文