首页 > 解决方案 > Active Record:如何一次从 3 个表中获取数据?

问题描述

我想sku_codeproductswh_namewarehouses表和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

标签: ruby-on-rails

解决方案


如果要使用单个查询加载所有三个记录,请使用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

推荐阅读