Rails 3,HABTM如何查询条件

我有奖项和类别,加入了Awards_Categories

我有2个类别。

我需要找到所有具有Category.id = 1的奖励,但不能找到Category.id = 2。 有些类别有一个或另一个,有些只有一个。 我想要一个类别1而不是类别2的奖项列表。

我有一个范围:

scope :in_categories, lambda { |categories| joins(:categories). where(:awards_categories => { :category_id => categories } ). select("DISTINCT awards.*") } 

这适用于以下查询:

 @awardsall = Award.in_categories([1 && 2]).order("name ASC") 

我试过了

 @awards_store = Award.in_categories([1]).order("name ASC") 

附:

  
  • store.info %> |
  • 编辑—我知道块不是我需要的。 这只是我试图找到一种方法使它工作。

    虽然这列出了所有的奖项,所有的奖项类别仍然是获奖的类别.id = 2,因为一些奖项同时具有

    有任何想法吗?

    对不起,没有测试它,但主要的想法是计算连接表中的行。

     scope :in_categories, lambda { |*categories| joins(:categories). where(:awards_categories => { :category_id => categories } ). where("(select count(distinct category_id) from awards_categories where category_id in (?)) = ?", categories, categories.size) } 

    并以这种方式使用它:

     @awardsall = Award.in_categories(1, 2).order("name ASC") @awards_store = Award.in_categories(1).order("name ASC") 

    如果你有awards_categories的模型,那么它看起来会更好:

     scope :in_categories, lambda { |*categories| joins(:categories). where(:awards_categories => { :category_id => categories } ). where("#{AwardCategory.where(:category_id => categories).count("distinct category_id").to_sql}=#{categories.size}") }