0

在我的商店模式我有以下幾點:在Rails 3.1,我如何才能找到指定的類別時,類別由關聯專賣店:的has_many,:通過

class Store < ActiveRecord::Base 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 

    scope :by_categories, lambda{|category_ids| 
    where(*stores have the following* => category_ids) unless category_ids.empty? 
    } 

我期待設置一個範圍在那裏我可以給它的多個或單個類別ID,並有屬於所有指定的類別範圍返回商店。

謝謝你的期待。

回答

2
class Store < ActiveRecord::Base 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 

    scope :by_categories, lambda { |category_ids| 
    joins(:categorizations).where('categorizations.category_id' => category_ids) unless category_ids.empty? 
    } 
end 

>> Store.by_categories([1,2]) 
=> SELECT "stores".* FROM "stores" INNER JOIN "categorizations" ON "categorizations"."store_id" = "stores"."id" WHERE "categorizations"."category_id" IN (1, 2)