1

我有一个类别、一个子类别和一个产品模型。

我有:

Category has_many Subcategories
Subcategory has_many Products
Subcategory belongs_to Category
Product belongs_to Subcategory

有没有办法有类似的东西

Category has_many Projects through Subcategories

?

“正常”导轨方式不起作用,因为“子类别”不属于产品,因此产品没有 subcategory_id 字段。相反,我需要查询类似于

SELECT * FROM products WHERE id IN category.subcategory_ids

有没有办法做到这一点?

谢谢,

尼古拉斯·霍克·伊萨萨

4

1 回答 1

5

如果您以“正常”的 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, ...>
于 2010-05-17T04:45:02.943 回答