繁体   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