我希望有一个简单的解决方案,不涉及find_by_sql,如果没有,那么我想这将不得不工作。

我发现这篇文章引用了这个:

Topic.find(:all, :conditions => { :forum_id => @forums.map(&:id) })

哪个是一样的

SELECT * FROM topics WHERE forum_id IN (<@forum ids>)

我想知道是否有一种方法可以不这样做,比如:

SELECT * FROM topics WHERE forum_id NOT IN (<@forum ids>)

当前回答

如果@forums为空,接受的解决方案将失败。为了解决这个问题,我不得不这么做

Topic.find(:all, :conditions => ['forum_id not in (?)', (@forums.empty? ? '' : @forums.map(&:id))])

或者,如果使用Rails 3+:

Topic.where( 'forum_id not in (?)', (@forums.empty? ? '' : @forums.map(&:id)) ).all

其他回答

上面的大多数答案应该足以满足您的需求,但如果您正在进行更多此类谓词和复杂组合,请查看Squeel。你可以这样做:

Topic.where{{forum_id.not_in => @forums.map(&:id)}}
Topic.where{forum_id.not_in @forums.map(&:id)} 
Topic.where{forum_id << @forums.map(&:id)}

你可能想看看Ernie Miller的meta_where插件。你的SQL语句:

SELECT * FROM topics WHERE forum_id NOT IN (<@forum ids>)

...可以这样表示:

Topic.where(:forum_id.nin => @forum_ids)

Railscasts的Ryan Bates制作了一个很好的视频来解释MetaWhere。

不确定这是否是你想要的,但在我看来,它肯定比嵌入式SQL查询更好。

这种方法优化了可读性,但在数据库查询方面效率不高:

# Retrieve all topics, then use array subtraction to
# find the ones not in our list
Topic.all - @forums.map(&:id)

仅供参考,在Rails 4中,你可以使用not语法:

Article.where.not(title: ['Rails 3', 'Rails 5'])

这些论坛id能够以一种实用的方式计算出来吗?例如,你能以某种方式找到这些论坛吗?如果是这样的话,你应该做一些事情

Topic.all(:joins => "left join forums on (forums.id = topics.forum_id and some_condition)", :conditions => "forums.id is null")

哪一个会比做一个SQL不在更有效