如果您以“正常”的 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
。
类别.rb
class Category < ActiveRecord::Base
has_many :subcategories
has_many :products, :through => :subcategories
end
子类别.rb
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
红宝石脚本\控制台
>> 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, ...>