2011-11-30 3 views
2

I이 활성 레코드 협회를 만들려면

항목 모델

class Item < ActiveRecord:Base 
    has_and_belongs_to_many :orders 
end 

와 주문 모델을 가지고

class Order < ActiveRecord:Base 
    has_and_belongs_to_many : items 
end 

HABTM이 처리됩니다 많은 항목을 가질 수있는 순서 의. 그러나 주문하는 품목의 수량을 저장하는 위치는 어디서입니까/어떻게합니까?

예 : Order1에는 Item1과 Item2가 있습니다. 이제 Order1과 같은 아이템과 관련된 수량을 저장하려고합니다. Item1은 두 개이고 Item2는 다섯 개 있습니다.

어떻게해야할까요?

답변

2

할 수있는 한 가지 방법은 has_many : through 연결을 사용하는 것입니다. 이것은 주. W 항목 간의 조인 테이블에 대해 독립적 인 엔티티를 작성합니다. 귀하의 경우 :

class Order < ActiveRecord::Base 
    has_many :invoices 
    has_many :items, :through => :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :order 
    belongs_to :items 

    #Put in the migration for this table a column for quantity 
end 

class Item < ActiveRecord::Base 
    has_many :invoices 
    has_many :orders, :through => :invoices 
end 

이 내가 믿는 문제를 해결할 것입니다. 그런 식으로 Item1과 관련된 Order1은 Invoice 테이블에 2의 수량을 가지며 Invoice 테이블에 별도의 수량 5를 갖는 Item2와 동일합니다.

자세한 내용은 The has_many :through Association 섹션의 A Guide to Active Record Associations에서 확인할 수 있습니다.