如果您以“普通的”RubyonRails的方式执行此操作,那么您描述的数据库将类似于这样。如果您的数据库结构不是这样的,我建议您阅读更多关于如何在RubyonRails中实现关联的信息,因为这是正确的方法(您应该使用
t.references :category
在您的迁移中,因为它是为了使您的引用更容易不被弄乱而设计的)。
+----------------+ +----------------+ +----------------+
| categories | | subcategories | | products |
+----------------+ +----------------+ +----------------+
| id | | id | | id |
| ... | | category_id | | subcategory_id |
| | | ... | | ... |
+----------------+ +----------------+ +----------------+
将此作为数据库结构,
has_many :products, :through => subcategories
作品
Category
模型。
RB分类
class Category < ActiveRecord::Base
has_many :subcategories
has_many :products, :through => :subcategories
end
子范畴
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end
产品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, ...>