簡體   English   中英

Rails 3,HABTM如何查詢條件

[英]Rails 3, HABTM how to query with conditions

我有獎項和類別,加入了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") 

附:

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

編輯---我知道塊不是我需要的。 這只是我試圖找到一種方法使它工作。

雖然這列出了所有的獎項,所有的獎項類別仍然獲得了類別.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}")
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM