Ruby on rails 活动记录:如何一次从3个表中获取数据?
我想从Ruby on rails 活动记录:如何一次从3个表中获取数据?,ruby-on-rails,Ruby On Rails,我想从产品提取sku代码,从仓库表提取仓库名,从产品仓库提取项目计数 我试过类似的东西 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"
产品
提取sku代码
,从仓库
表提取仓库名
,从产品仓库
提取项目计数
我试过类似的东西
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\u load
:
Product.all.eager_load(:product_warehouses, :warehouses)
假设您要在控制台中打印sku_代码、wh_名称和item_计数。首先将所有产品加载到变量中:
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
如果要通过单个查询加载所有三条记录,请使用
eager\u load
:
Product.all.eager_load(:product_warehouses, :warehouses)
假设您要在控制台中打印sku_代码、wh_名称和item_计数。首先将所有产品加载到变量中:
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
这是一个很好的资源,介绍了连接、包含、快速加载和预加载之间的区别:谢谢。但是您能解释一下如何获取“sku代码”(产品)、“仓库名称”(仓库)和“物品计数”(产品仓库)吗在您建议的快速加载之后。这是一个关于连接、包含、快速加载和预加载之间差异的很好的资源:谢谢。但是您能否解释一下,在您建议的快速加载之后,如何获取“sku_代码”(产品)、“仓库名称”(仓库)和“物品计数”(产品仓库)。