【说明:资料来自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. [codeVS1204] 单词背诵

    题目描述 灵梦有n个单词想要背,但她想通过一篇文章中的一段来记住这些单词. 文章由m个单词构成,她想在文章中找出连续的一段,其中包含最多的她想要背的单词(重复的只算一个).并且在背诵的单词量尽量多的情 ...

  2. 【HDOJ6298】Maximum Multiple(数论)

    题意:给定n,求x,y,z三个整数,使得x|n,y|n,z|n,且xyz最小 n<=1e6 思路: 不定方程1/x+1/y+1/z=1 只有(2,3,6)(2,4,4) (3,3,3)三组正整数 ...

  3. hdu 2736 Average distance

    传送门 Average distance Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  4. Swift 了解

    本篇仅于个人小记,记录个人不熟悉的知识点儿.如若要了解更全,请前往如下网址:http://www.runoob.com/swift/swift-arrays.html 1.Swift 标记 分号:Sw ...

  5. JavaOne Online Hands-on Labs

    http://www.oracle.com/technetwork/java/index-156938.html

  6. 如何使用shell收集linux系统状态,并把结果发给远端服务器

    第一步:收集系统当天状态 load状态 内存状态 cpu状态 jvm相关信息:jstat jstack 网络信息 硬盘信息 第二步:发送到远端服务器 使用curl.wget.定义接口. https:/ ...

  7. Centos5设置静态IP地址

    1.设置静态IP地址,修改/etc/sysconfig/network-scripts/ifcfg-eth0的内容: DEVICE=eth0 #网卡对应的设备别名 BOOTPROTO=static # ...

  8. NODE安装N管理出错

    Windows不支持,反正我在Linux上用过,从此脱离Win坑!

  9. C++卷积神经网络实例:tiny_cnn代码具体解释(6)——average_pooling_layer层结构类分析

    在之前的博文中我们着重分析了convolutional_layer类的代码结构.在这篇博文中分析相应的下採样层average_pooling_layer类: 一.下採样层的作用 下採样层的作用理论上来 ...

  10. 各项异性滤波简单介绍Anisotropic Filtering(AF)

    本文主要整理简绍来自互联网的各项异性滤波的知识. 原文链接:http://www.linuxgraphics.cn/graphics/using_anisotropic_texture_filteri ...