首页 > 解决方案 > 创建一个 JSON 对象发送回客户端

问题描述

感谢到目前为止帮助过我的所有人。我只有最后一个问题,我想我可以取消这个学习项目。

我想创建一个 JSON 对象像这样:

 [
     {name: 'xbox',
      upc: '1313413412',
      available_on: '12/31/18',
      properties: [
       {name: 'material',
        value: 'plastic'
       },
       {name: 'color',
        value: 'white'
       },
      ]
     },
     {name: 'nintendo',
      upc: '1313413412',
      available_on: '12/31/18',
      properties: [
       {name: 'material',
        value: 'plastic'
       },
       {name: 'color',
        value: 'black'
       },
      ]
     }
]

我有 3 个表 product、properties、product_properties

我通过这样做加入他们是我的控制器:

@products = Product.joins(:properties, :product_properties)

 @products.each do |product| 

 end

但我不知道从这里去哪里。我为新问题道歉。我只是想边做边学。我的关联设置正确。

架构:

ActiveRecord::Schema.define(version: 2018_09_24_163027) do

  create_table "product_properties", force: :cascade do |t|
    t.string "value"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "product_id"
    t.integer "property_id"
    t.index ["product_id"], name: "index_product_properties_on_product_id"
    t.index ["property_id"], name: "index_product_properties_on_property_id"
  end

  create_table "products", force: :cascade do |t|
    t.string "name"
    t.string "upc"
    t.datetime "available_on"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "properties", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "product_id"
    t.index ["product_id"], name: "index_properties_on_product_id"
  end

end

再次感谢您能给我的任何帮助。

标签: ruby-on-railsruby-on-rails-5

解决方案


@products.map do |product|
  {
    name: product.name,
    properties: product.product_properties.map do |product_property|
      {
        name: product_property.property.name,
        value: product_property.value
      }
    end
  }
end.to_json

随意放置您需要的任何属性。你提到你需要一个 JSON,但你实际上粘贴了一个 Ruby 哈希,我.to_json在最后添加了一个。


推荐阅读