당신은 이것을 '정상'루비 온 레일스 방식으로 할 경우, 당신이 설명하는 데이터베이스가 다음과 같이 보일 것입니다. 데이터베이스가 이와 같이 구조화되어 있지 않다면 올바른 방법이므로 Ruby on Rails에서 연관 짓는 방법에 대해 더 많이 읽으십시오 (그리고 쉽게 마이그레이션 할 수 있도록 설계되었으므로 마이그레이션에 t.references :category
을 사용해야합니다). 엉망진창.) 데이터베이스 구조 등이 함께
+----------------+ +----------------+ +----------------+
| categories | | subcategories | | products |
+----------------+ +----------------+ +----------------+
| id | | id | | id |
| ... | | category_id | | subcategory_id |
| | | ... | | ... |
+----------------+ +----------------+ +----------------+
의
Category
모델의
has_many :products, :through => subcategories
작품. 별도의 모델로
Category.rb
class Category < ActiveRecord::Base
has_many :subcategories
has_many :products, :through => :subcategories
end
Subcategory.rb
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end
Product.rb
class Product < ActiveRecord::Base
belongs_to :subcategory
has_one :category, :through => :subcategory # don't need this, but it does work
end
루비 스크립트 \ 콘솔
>> c = Category.create
=> #<Category id: 1, ...>
>> c.subcategories.create
=> #<Subcategory id: 1, category_id: 1, ...>
>> p = s.products.create
=> #<Product id: 1, subcategory_id: 1, ...>
>> c.products
=> [#<Product id: 1, subcategory_id: 1, ...>]
>> p.category # if you have the has_one assocation
=> #<Category id: 1, ...>
종류와 하위 범주는 이상한 찾고 나무 있도록합니다. 각각 하나의 레벨 만 있습니까, 아니면 하위 카테고리 객체가 서로 중첩 될 수 있습니까? – jdl
거기에 단 한 수준 것입니다. – Hock
대부분의 혼란은 XXX_id 필드가 내가 속한 모델에 있다고 생각하는 것으로부터 비롯된 것이라고 생각합니다. 그렇지 않습니다. belongs_to라고하는 모델에는 참조 필드가 있습니다. – Samuel