代码之家  ›  专栏  ›  技术社区  ›  Hock

单程有很多次

  •  1
  • Hock  · 技术社区  · 16 年前

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

    我有:

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

    有没有一种方法

    Category has_many Projects through Subcategories
    

    ?

    “Normal”Rails方式不起作用,因为“Subcategory”不属于产品,所以产品没有Subcategory_id字段。相反,我需要查询

    SELECT * FROM products WHERE id IN category.subcategory_ids
    

    有办法吗?

    谢谢,

    尼古拉·伊萨扎

    1 回复  |  直到 16 年前
        1
  •  5
  •   Samuel    16 年前

    如果您以“普通的”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, ...>