ruby-on-rails - 创建一个 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
再次感谢您能给我的任何帮助。
解决方案
@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
在最后添加了一个。
推荐阅读
- r - Blogdown 和 hugo 不解析 Markdown 中的 html 标签
- drake - 对于多机器人仿真,我们是否需要多个多体植物?
- .htaccess - 在 RewriteCond 中没有扩展名的 REQUEST_FILENAME
- loops - BASIC:了解我自己的 Ada 代码。查找将整数除以无分数的数字
- c++ - C++中的指针向量
- markdown - 为什么我的 Rmarkdown ioslides 中不显示 ggplotly 函数
- react-native - 在 TabBottomNavigation React Native 上添加图标
- triggers - 更新触发器后用 null 替换空字符串将该列中的所有数据更新为 null
- python - 在浏览器中打开 JavaScript 以继续
- python-3.x - 如何根据不同变量的值命名类变量?