我最近刚开始学习RoR,我正在创建一个爱好项目。
简单介绍一下背景知识:每个客户都有一个账号来标识。每个产品销售都有一个帐号,产品表包含所有特定的产品数据。
我的问题是-与我现在的格式,这是正确的方式,我应该链接这些表?我遇到的一个问题是根据产品专业筛选一组销售。假设我有一个客户,我只想查看专业为"商业"的产品销售情况,我该如何过滤这些数据?看到我创建的范围-但我不确定如何使用它。
class Product < ActiveRecord::Base
has_many :product_sales, :primary_key => :prodnum, :foreign_key => :prodnum
has_many :customers, through: :sales
scope :commercial_products, -> { where(major: 'Commercial') }
end
class ProductSale < ActiveRecord::Base
belongs_to :customer, :foreign_key => :account
belongs_to :product, :foreign_key => :prodnum, :primary_key => :prodnum
end
class Customer < ActiveRecord::Base
has_many :product_sales, :primary_key => :account, :foreign_key => :account
has_many :products, through: :product_sales
end
和我的schema
create_table "customers", force: :cascade do |t|
t.integer "account"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "product_sales", force: :cascade do |t|
t.integer "account"
t.string "month"
t.string "prodnum"
t.integer "sales"
t.integer "qtyshipped"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "pcatcode"
t.string "pcatname"
t.string "major"
t.string "prodline"
t.string "brand"
t.string "tier"
t.string "prodnum"
t.string "proddesc"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
…我有一个客户,我只想查看专业为"商业"的产品销售情况,我该如何过滤这些数据?
应该这样做:
@customer.product_sales.where(product: {major: 'Commercial'})
p。你的模型看起来是正确的,但是这一点
has_many :customers, through: :sales
# Probably you meant: through: product_sales