我有一种搜索方法,我希望为用户提供排除{I}搜索模型的选项,该搜索具有特定主题。 Cases
模型与Search
有两个独立的多对多关系,设置如下:
Topics
要搜索包含某些主题的案例,我使用了此代码。
class Search < ActiveRecord::Base
include ViewersHelper
has_many :included_topics, through: :including_topics, source: :topic
has_many :excluded_topics, through: :excluding_topics, source: :topic
has_many :including_topics
has_many :excluding_topics
此查询的相反之处是使排除的主题有效吗?
根据this question,我尝试了以下内容:
ids = included_topics.pluck(:id)
cases = cases.includes(:topics).where('topics.id' => ids)
但是rails会从该查询中给出以下错误:
ids = excludes_topics.pluck(:id)
cases = cases.includes(:topics).where('topics.id NOT IN (?)', ids)
第6行只是在引用中执行搜索的ActiveRecord::StatementInvalid in Searches#show
Showing ../app/views/searches/show.html.erb where line #6 raised:
SQLite3::SQLException: no such column: topics.id: SELECT "cases".* FROM "cases" WHERE (topics.id NOT IN (2)) LIMIT 20 OFFSET 0
变量的第一行
答案 0 :(得分:2)
您可以使用
ids = excludes_topics.pluck(:id)
cases = Case.joins(:topics).where('topics.id NOT IN (?)', ids)
答案 1 :(得分:0)
这是我使用两个查询创建的解决方案:
ids = excludes_topics.pluck(:id)
included_cases_ids = Case.all.includes(:topics).where('topics.id' => ids).pluck(:id)
cases = cases.where.not('id' => included_cases_ids)