8

I have this models in ruby on rails

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

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

Product model:

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

gets:

{
 "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.

4

2 回答 2

15

我不确定您的产品可以具有哪些属性,但我会尝试以下操作:

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 嵌套在分支下,如下所述:

json.branch do
   ...
end

我刚刚删除了那个。

于 2014-01-06T23:20:45.823 回答
0

这是来自文档(“this”是“json.array!方法)http://www.rubydoc.info/github/rails/jbuilder/Jbuilder:array

一般只需要对顶级数组使用此方法即可。如果你有命名数组,你可以这样做:

json.people(@people) do |person|
  json.name person.name   
  json.age calculate_age(person.birthday) 
end

{ "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }

我使用数组有意想不到的行为!和建议的定期迭代完美地工作,使我的代码非常可读:

json.user do
  json.email @user.email
  json.devices @user.devices do |device|
    json.partial! 'devices/device', device: device
  end
end
于 2016-12-07T18:21:26.777 回答