如果你这样做“正常” Ruby on Rails的方式,您所描述的数据库会是这个样子。如果你的数据库不是这样构建的,我建议你阅读更多关于如何在Ruby on Rails中完成关联的方法,因为这是正确的方式(并且你应该在你的迁移中使用t.references :category
,因为它的目的是使它不容易弄乱你的参考)。
+----------------+ +----------------+ +----------------+
| categories | | subcategories | | products |
+----------------+ +----------------+ +----------------+
| id | | id | | id |
| ... | | category_id | | subcategory_id |
| | | ... | | ... |
+----------------+ +----------------+ +----------------+
以此为你的数据库的结构,has_many :products, :through => subcategories
作品为Category
模型。
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
Ruby脚本\控制台
>> 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 2010-05-17 04:39:01
我想只会有一个级别。 – Hock 2010-05-17 04:40:39
我认为你的大部分困惑都来自于你认为XXX_id字段在你名为belongs_to的模型上,但事实并非如此。说belongs_to的模型有参考字段。 – Samuel 2010-05-17 04:48:20