一种方式有很多通过

时间:2010-05-17 03:48:05

标签: ruby-on-rails has-many-through

我有一个分类,一个子类别和一个产品型号。

我有:

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

有没有办法像

那样
Category has_many Projects through Subcategories

“普通”rails方式不起作用,因为“subategory”不属于产品,因此产品没有subategory_id字段。相反,我需要查询类似

SELECT * FROM products WHERE id IN category.subcategory_ids

有办法吗?

谢谢,

NicolásHockIsaza

1 个答案:

答案 0 :(得分: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模型。

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, ...>