2013-01-09 28 views
6

类别之间的这种关系,产品&品牌的Rails的habtm加入

class Brand < ActiveRecord::Base 
    has_many :products 
end 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    belongs_to :brand 
end 

如何选择跟这个有关系的所有类别的指定品牌? 我试试这个,但得到一个错误

b = Brand.find(1) 
Category.joins(:products).where(:products => b.products) 

回答

7

你做了与正确的事的加入,只需添加一个更复杂的,其中定义:

Category.joins(:products).where(:products => {:brand_id => 1}) 
4

有争议HABTM的很少,甚至根本,良好的设计和国际海事组织只是唯一的Rails有错。

引入外部参照表加入产品类别和使用的has_many:通过对关系的双方,所以你最终与

class Brand < ActiveRecord::Base 
    has_many :products 
    has_many categories :through => products # This is now allowed in Rails 3.x and above 
end 

class Category < ActiveRecord::Base 
    belongs_to :product_category 
    has_many :products :through => product_category 
end 

class Product < ActiveRecord::Base 
    belongs_to :brand 
    belongs_to :product_category 
    has_many :categories :through => product_category 
end 

class ProductCategory < ActiveRecord::Base 
    has_many :products 
    has_many :categories 
end 

这使你的代码重新量最少的最佳灵活性保理你加一个更加直观的路径来获得你需要的关系,任何一方的所有数据,将让你达到以下

b = Brand.find(1) 
b.categories.all 

更新 以上是完全未经测试的代码,我刚纠正了我犯的一个明显愚蠢的错误。如果你有这个实施任何问题,然后再回来