Rails 3, HABTM how to query with conditions

眉间皱痕 提交于 2020-01-01 16:42:10

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/8705690/rails-3-habtm-how-to-query-with-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!