简体   繁体   中英

Rails 3, HABTM how to query with conditions

I have Awards and Categories, joined with Awards_Categories

I have 2 Categories.

I need to find all the Awards that have Category.id = 1, but not 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.

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM