【问题标题】:Rails 3, HABTM how to query with conditionsRails 3、HABTM如何带条件查询
【发布时间】:2012-01-02 21:49:57
【问题描述】:

我有奖项和类别,与 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 %>

编辑--- 我知道这个块不是我需要的。这只是我试图找到一种让它发挥作用的方法。

虽然这列出了所有奖项和所有奖项类别,但它仍在获取 category.id = 2 的奖项,因为有些奖项同时拥有这两个奖项

有什么想法吗?

【问题讨论】:

  • 有人吗?如果有人知道如何让它工作,仍然需要帮助......

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

不好意思,没测试,主要思路是统计连接表中的行数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多