2016-06-24 2 views
0

나는 최근에 RoR을 배우기 시작했고 취미 프로젝트를 만들고 있습니다.내 ActiveRecord 관계에 대한 리뷰를 찾고

빠른 배경 : 각 고객은 계정 번호로 식별됩니다. 각 제품 판매에는 계정 번호가 있으며 제품 테이블에는 모든 특정 제품 데이터가 들어 있습니다.

제 질문은 - 지금 가지고있는 형식으로,이 테이블을 연결해야하는 적절한 방법입니까? 내가 가지고있는 문제 중 하나는 제품 주요을 기반으로 한 판매 그룹을 필터링하는 것입니다. 고객이있어 전공이 "상업적"인 곳에서만 제품 판매를보고 싶습니다.이 데이터를 필터링하려면 어떻게해야합니까? 제가 만든 범위를보십시오 - 그러나 그것을 사용하는 방법을 모르겠습니다.

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 
+0

난 당신이 액티브 레코드 열거 형을 살펴 (걸릴 추천 http://api.rubyonrails.org/v4.1/classes/ActiveRecord /Enum.html)을 사용하면 String 대신에 더 많은 성능을 가진 정수를 DB에 저장할 수 있으며, 예를 들어'products.commercial'과 같은 편리한 메소드에 액세스 할 수 있습니다. – Leito

답변

0

은 ... 나는 고객이 있고 난 단지 주요는 "상업용"입니다 제품 판매를 보려는 어떻게이 데이터를 필터링 가야합니까 내 스키마 ?

이 그것을 수행해야합니다

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

PS합니다. 귀하의 모델은 올바른 보이지만, 당신은 전공의 AA 유한 집합이있는 경우이 비트

has_many :customers, through: :sales 

# Probably you meant: through: product_sales 
+0

고마워요 - 전공이 "그런 칼럼"을 얻지 못했지만 이것은 작동하지 않았습니다. 그러나 이것은 약간의 연구를 수행하고 @ customer.product_sales.joins (: product) .where (: products => {: major => 'Residential'})로 올바른 방향으로 나를 이끌었습니다. 이것은 제가 원했던 것처럼 작동합니다. 고맙습니다. – Kevin

+0

예금, 가입하는 것을 잊었습니다 ... – Uzbekjon

관련 문제