2014-10-29 4 views
0

나는 sty가 내 DB를 구축하는 방법에있어서 틀림에 틀림 없다고 알고 있지만, 잠시 시간을내어이 질문에 대답 해주십시오 : 저는 1 명의 사용자가 쇼핑 목록을 가지고있는 슈퍼마켓 모델을 만들고 있습니다. 각 목록에는 많은 제품이 있습니다. 그래서 내가 할 것입니다 :레일 협회 belongs_to

class User < ActiveRecord::Base 
    has_many :lists 
end 

class List < ActiveRecord::Base 
    belongs_to :user 
    has_many :products 
end 

class Product < ActiveRecord::Base 
    ???? 
end 

목록은 여러 제품이 있지만 제품 목록에 속하지 않습니다. 많은 목록을 가진 사용자와 많은 제품을 가진 목록을 가지려면 어떻게해야합니까? 안부,

답변

0

has_many through를 통해 링크하는 클래스가 있습니다.

class ListItem < ActiveRecord::Base 
    belongs_to :list 
    belongs_to :product 
end 

class List < ActiveRecord::Base 
    belongs_to :user 
    has_many :list_items 
    has_many :products, through: :list_items 
end 
+0

내가 할 수있는 :

class User < ActiveRecord::Base has_many :lists end class List < ActiveRecord::Base belongs_to :user has_and_belongs_to_many :products end class Product < ActiveRecord::Base has_and_belongs_to_many :lists end 

은 물론, 마이그레이션 테이블을 조인 추가해야 나는 이것을하기 위해 여분의 수업이 필요하다고 생각하지 않는다. 이 연상 협회는 유용하며 추측하는 모든 시간에 발생합니다. 쇼핑 목록에 항목이있는 사용자 목록을 관리해야합니까, 진행 방법입니까? – Yann

+0

대신 db 테이블은 있지만 모델은없는 has_and_belongs_to_many를 사용할 수 있습니다. –

0

추가 클래스가 필요하지 않습니다. 레일이 경우에 has_and_belongs_to_many_association

당신이 관리 할 수 ​​있습니다, 그것은 다음과 같습니다

create_table :lists_products, id: false do |t| 
    t.belongs_to :list 
    t.belongs_to :product 
end