2012-01-02 71 views
3

我有獎項和類別,加入獎勵_分類Rails 3,HABTM如何查詢條件

我有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") 

有了:

<% @awards_store.each do |store| %> 
     <li><%= link_to store.name, award_path(store), :title => store.info %> | 
     <% store.categories.each do |cat| %> 
      <%= cat.id%> 
     <% end %> 
    </li> 
<% end %> 

編輯--- 我知道該塊不是我所需要的。這只是我嘗試找到一種方法來實現它的工作。

雖然這列出了所有的獎項,所有的獎項已經category.id = 2,因爲一些獎項兼得

任何想法,其猶搶奪獎勵嗎?

+0

有人嗎?如果有人知道如何得到這個工作,仍然需要幫助... – 2012-01-03 05:47:07

回答

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}") 
    }