如何使用 ActiveRecord/Rails 表达 NOT IN 查询? [英] How to express a NOT IN query with ActiveRecord/Rails?

查看:32
本文介绍了如何使用 ActiveRecord/Rails 表达 NOT IN 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个不涉及 find_by_sql 的简单解决方案,如果没有,那么我想这将必须起作用.

I'm hoping there is a easy solution that doesn't involve find_by_sql, if not then I guess that will have to work.

我发现这篇文章引用此:

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

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

我想知道是否有办法做到 NOT IN ,例如:

I am wondering if there is a way to do NOT IN with that, like:

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

推荐答案

Rails 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]

这篇关于如何使用 ActiveRecord/Rails 表达 NOT IN 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆