【说明:资料来自https://robots.thoughtbot.com/activerecords-wherenot

ActiveRecord's where.not

January 24, 2014

Rails 4.0 introduced a helpful new method for ActiveRecord queries: where.not. It can make clunky queries easier to read.

Usage

This query:

User.where.not(name: 'Gabe')

is effectively the same as this:

User.where('name != ?', 'Gabe')

It’s “effectively” the same because where.not has some extra juice: it will fully qualify the column name with the table name, continue to work if the table or column get aliased (during a left outer join clause with includes), and will continue to work if the database implementation is switched.

I’ve usually seen it used for NOT NULL queries:

# Old and busted
# User.where('name IS NOT NULL')
# New hotness
User.where.not(name: nil)

But it works with arrays too:

# Without `where.not`
# Something.where("name NOT IN ?", User.unverified.pluck(:name))
# With `where.not`
Something.where.not(name: User.unverified.pluck(:name))

That example takes advantage of the fact that ActiveRecord automatically uses IN (or in this case NOT IN) if the value you’re querying against is an array.

Complex usage

Here’s a more complex example:

class Course < ActiveRecord::Base
def self.with_no_enrollments_by(student)
includes(:enrollments).
references(:enrollments).
where.not(enrollments: { student_id: student.id })
end
end

You can ignore the first two lines, which tell ActiveRecord that we’re going through the enrollments table (student has_many :courses, through: :enrollments). The method finds courses where the course has no enrollments by the student. It is the complement to student.courses.

Without where.not, it would look like this:

def with_no_enrollments_by(student)
includes(:enrollments).
references(:enrollments).
where('enrollments.student_id != ?', student.id)
end

I prefer the pure-Ruby approach of the where.not version instead of the string SQL of the latter because it’s easier to read and it’s easier to change later.

What’s next

If you found this post helpful, I recommend our post on null relations or a close reading of the official ActiveRecord docs.

Rails - ActiveRecord的where.not方法详解(copy)的更多相关文章

  1. session的使用方法详解

    session的使用方法详解 Session是什么呢?简单来说就是服务器给客户端的一个编号.当一台WWW服务器运行时,可能有若干个用户浏览正在运正在这台服务器上的网站.当每个用户首次与这台WWW服务器 ...

  2. Kooboo CMS - Html.FrontHtml[Helper.cs] 各个方法详解

    下面罗列了方法详解,每一个方法一篇文章. Kooboo CMS - @Html.FrontHtml().HtmlTitle() 详解 Kooboo CMS - Html.FrontHtml.Posit ...

  3. HTTP请求方法详解

    HTTP请求方法详解 请求方法:指定了客户端想对指定的资源/服务器作何种操作 下面我们介绍HTTP/1.1中可用的请求方法: [GET:获取资源]     GET方法用来请求已被URI识别的资源.指定 ...

  4. ecshop后台增加|添加商店设置选项和使用方法详解

    有时候我们想在Ecshop后台做个设置.radio.checkbox 等等来控制页面的显示,看看Ecshop的设计,用到了shop_config这个商店设置功能 Ecshop后台增加|添加商店设置选项 ...

  5. (转)Spring JdbcTemplate 方法详解

    Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...

  6. C++调用JAVA方法详解

    C++调用JAVA方法详解          博客分类: 本文主要参考http://tech.ccidnet.com/art/1081/20050413/237901_1.html 上的文章. C++ ...

  7. windows.open()、close()方法详解

    windows.open()方法详解:         window.open(URL,name,features,replace)用于载入指定的URL到新的或已存在的窗口中,并返回代表新窗口的Win ...

  8. CURL使用方法详解

    php采集神器CURL使用方法详解 作者:佚名  更新时间:2016-10-21   对于做过数据采集的人来说,cURL一定不会陌生.虽然在PHP中有file_get_contents函数可以获取远程 ...

  9. JAVA 注解的几大作用及使用方法详解

    JAVA 注解的几大作用及使用方法详解 (2013-01-22 15:13:04) 转载▼ 标签: java 注解 杂谈 分类: Java java 注解,从名字上看是注释,解释.但功能却不仅仅是注释 ...

随机推荐

  1. Hotel(poj 3667)

    题意:询问区间最长连续空串 /* 用线段树维护区间最长连续左空串和右空串 */ #include<cstdio> #include<iostream> #define N 50 ...

  2. msp430项目编程25

    msp430中项目---带有断电保护的电子密码锁 1.I2C工作原理 2.I2C通信协议 3.代码(显示部分) 4.代码(功能实现) 5.项目总结 msp430项目编程 msp430入门学习

  3. Spring注解 @Component、@Repository、@Service、@Controller @Resource、@Autowired、@Qualifier 解析

    @Repository.@Service.@Controller 这几个是一个类型,其实@Component 跟他们也是一个类型的 Spring 2.5 中除了提供 @Component 注释外,还定 ...

  4. css三大布局

    标准流: 从左到右,从上到下块级元素独占一行,行内元素碰到父盒子边缘换行 浮动: 特点 1 元素浮动之后不占据原来的位置(脱标),变成立体,下面可以有东西,只影响下面的 2 浮动的盒子在一行上显示 3 ...

  5. Spring Boot应用的启动和停止(Spring Boot应用通过start命令启动)

    Spring Boot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行.产品级别的基于S ...

  6. 中间件序列TDATASET为BUFFER演示代码

    procedure SendStream(const AStream: TStream);var Buffer: array[0..4095] of Byte; // 每包最大4K StartPos, ...

  7. google官方建议使用的网站性能测试工具

    转自:http://www.laokboke.net/2013/05/12/google-official-recommended-site-performance-testing-tools/ 最近 ...

  8. 代理服务器squid简介

    Squid 是一个高性能.开源的代理缓存服务器和 Web 缓存进程,支持 FTP.Internet Gopher.HTTPS 和 SSL 等多种协议.它通过一个非阻塞的.I/O 事件驱动的单一进程处理 ...

  9. python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别和基本使用

    1.解析速度:ElementTree在 Python 标准库中有两种实现.一种是纯 Python 实现例如 xml.etree.ElementTree ,另外一种是速度快一点的 xml.etree.c ...

  10. Client使用c#和odp.net连接server oracle

    http://blog.csdn.net/educast/article/details/6605655 Oracle.DataAccess.dll有2.X版本和4.X版本,VS2008开发用2.X ...