gpt4 book ai didi

ruby-on-rails - Rails 3, HABTM 如何带条件查询

转载 作者:行者123 更新时间:2023-12-04 23:51:50 26 4
gpt4 key购买 nike

我有 Awards 和 Categories,加入了 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 %>

编辑---我知道 block 不是我需要的。这只是我试图找到一种方法使其发挥作用的尝试。

虽然这列出了所有的奖项和所有的奖项类别,但它仍然吸引着 category.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}")
}

关于ruby-on-rails - Rails 3, HABTM 如何带条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com