寻找我的ActiveRecord关系的评论

时间:2016-06-24 14:10:11

标签: ruby-on-rails activerecord

我最近刚开始学习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

和我的架构

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

1 个答案:

答案 0 :(得分:0)

  

...我有一个客户,我只想查看主要是“商业”的产品销售,我该如何过滤这些数据?

这应该这样做:

@customer.product_sales.where(product: {major: 'Commercial'})

PS。你的模型看起来是正确的,但这一点

has_many :customers, through: :sales

# Probably you meant: through: product_sales