ruby-on-rails - Active Record:如何一次从 3 个表中获取数据?
问题描述
我想sku_code
从products
、wh_name
从warehouses
表和item_count
从获取product_warehouses
。
我尝试了类似的东西
Product.all.includes(:product_warehouses)
但不工作:(
以下是我的表的架构
create_table "product_warehouses", force: :cascade do |t|
t.integer "product_id"
t.integer "warehouse_id"
t.integer "item_count"
t.integer "threshold"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_product_warehouses_on_product_id"
t.index ["warehouse_id"], name: "index_product_warehouses_on_warehouse_id"
end
create_table "products", force: :cascade do |t|
t.string "sku_code"
t.string "name"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "warehouses", force: :cascade do |t|
t.string "wh_code"
t.string "wh_name"
t.string "pin"
t.integer "max_cap"
t.integer "threshold"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
下面是表之间的关系:
class Product < ApplicationRecord
has_many :product_warehouses
has_many :warehouses, through: :product_warehouses
end
class ProductWarehouse < ApplicationRecord
belongs_to :product
belongs_to :warehouse
end
class Warehouse < ApplicationRecord
has_many :product_warehouses
has_many :products, through: :product_warehouses
end
解决方案
如果要使用单个查询加载所有三个记录,请使用eager_load
:
Product.all.eager_load(:product_warehouses, :warehouses)
假设您要在控制台中打印 sku_code、wh_name 和 item_count。首先将所有产品加载到变量中:
products = Product.all.eager_load(:product_warehouses, :warehouses)
然后遍历记录并打印出每个值:
products.each do |product|
puts "sku_code: #{product.sku_code}"
product.product_warehouses.each do |product_warehouse|
puts "item_count: #{product_warehouse.item_count}"
puts "wh_code: #{product_warehouse.warehouse.wh_code}"
end
end
推荐阅读
- c++ - 为什么实际节点必须是指针?
- javascript - 如何摆脱 React Web 应用程序中的内存泄漏
- angular - Angular .htaccess 重写规则而不更改 url
- python - 同时在索引和列上重新索引
- reactjs - React useEffect 重启定时器
- docker - Minikube 上具有公共可用 TCP 连接的主机服务?
- .net-core - .NET Core 是否有 64 个 vCPU 限制?
- python - 在 python 字典中附加两个或多个零
- numpy - 尝试规范化 numpy.array 中的列时出现意外行为(版本 1.17.4)
- python - Pandas 查询数据框的性能差异