简体   繁体   English

Rails 3,HABTM如何查询条件

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

I have Awards and Categories, joined with Awards_Categories 我有奖项和类别,加入了Awards_Categories

I have 2 Categories. 我有2个类别。

I need to find all the Awards that have Category.id = 1, but not Category.id =2. 我需要找到所有具有Category.id = 1的奖励,但不能找到Category.id = 2。 Some categories have one or the other, some have just one. 有些类别有一个或另一个,有些只有一个。 I want a list of the Awards that have category 1 but not category 2. 我想要一份包含类别1而不是第2类的奖项列表。

I have a scope: 我有一个范围:

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

And this works with a query like: 这适用于以下查询:

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

I have tried 我努力了

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

With: 附:

<% @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--- I know the block is not what I need. 编辑---我知道块不是我需要的。 it is just my attempt at finding a way to make it work. 这只是我试图找到一种方法使它工作。

And while this lists all the awards, and all the award categories its still grabbing awards that have category.id = 2 because some awards have both 虽然这列出了所有的奖项,所有的奖项类别仍然获得了类别.id = 2的奖项,因为一些奖项同时具有

any ideas? 有任何想法吗?

Sorry, didn't test it, but the main idea is to count the rows in the connecting table. 对不起,没有测试它,但主要的想法是计算连接表中的行。

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

and use it this way: 并以这种方式使用它:

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

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

If you have a model for awards_categories, then it will look better: 如果你有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