我希望有一个简单的解决方案,不涉及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>)

当前回答

导轨 4+:

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

Rails 3:

Topic.where('id NOT IN (?)', Array.wrap(actions))

其中actions是一个数组,包含:[1,2,3,4,5]

其他回答

要扩展@Trung Lê答案,在Rails 4中您可以执行以下操作:

Topic.where.not(forum_id:@forums.map(&:id))

你可以更进一步。 如果你需要先过滤发布的主题,然后过滤掉你不想要的id,你可以这样做:

Topic.where(published:true).where.not(forum_id:@forums.map(&:id))

Rails 4让它变得更简单!

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

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

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

你可以在你的条件下使用sql:

Topic.find(:all, :conditions => [ "forum_id NOT IN (?)", @forums.map(&:id)])

最初的帖子特别提到了使用数字id,但我来这里寻找用字符串数组做NOT IN的语法。

ActiveRecord也会很好地为你处理:

Thing.where(['state NOT IN (?)', %w{state1 state2}])

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

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