2012-01-02 8 views
3

Awards_Categoriesと結合した賞とカテゴリRails 3、HABTM条件を照会する方法

私は2つのカテゴリーを持っています。

Category.id = 1ではなくCategory.id = 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") 

私は、カテゴリ1ではなく、カテゴリ2

を持っている賞のリストは、私がスコープを持って欲しいです

@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 %> 

EDIT --- 私はブロックが私が必要なものではないことを知っています。それを機能させる方法を見つけることが私の試みです。

そして、これはいくつかの賞を両方

任意のアイデアを持っているので、= 2 category.idてきたそのまだつかん賞を、すべての賞を一覧表示し、すべての賞のカテゴリしばらく?

+0

誰ですか?誰かがこれを動作させる方法を知っているなら、まだ助けが必要です... –

答えて

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}") 
    } 
関連する問題