2013-01-09 29 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 

更新 以上是完全未經測試的代碼,我剛糾正了我犯的一個明顯愚蠢的錯誤。如果你有這個實施任何問題,然後再回來