【说明:资料来自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. numpy模块

    NumPy简介: NumPy 是高性能科学计算和数据分析的基础包:它是pandas等其他工具的基础. NumPy的主要功能: 1. ndarray,一个多维数组结构,高效且节省空间 (最主要的功能) ...

  2. 使用HttpWebRequest post数据时要注意UrlEncode

    今天在用HttpWebResponse类向一个远程页面post数据时,遇到了一个怪问题:通过对比自己post的参数和服务器接收到的值,发现参数中的一个+号被替换成了空格. 造成这个错误的原因在于+号在 ...

  3. Django的form,model自定制

    一.Form组件原理: django框架提供了一个form类,来处理web开发中的表单相关事项.众所周知,form最常做的是对用户输入的内容进行验证,为此django的forms类提供了全面的内容验证 ...

  4. 2015轻院校赛 D 社交网络(排列组合)

    http://acm.zznu.edu.cn/problem.php?id=1964 题目描述 输入 输出 样例输入 2 2 1 0 1 1 0 3 1 0 1 1 1 0 1 1 1 0 样例输出 ...

  5. python 爬虫(转,我使用的python3)

      原文地址:http://blog.csdn.net/pi9nc/article/details/9734437 [Python]网络爬虫(一):抓取网页的含义和URL基本构成 分类: 爬虫 Pyt ...

  6. java 读取数据库数据转化输出XML输出在jsp页面

    因为老师实验报告要求,搭建服务端解析XML 下面代码实现转化XML格式也是在网上找的转化代码 输出在jsp页面以便于客户端解析是自己写的 一个类就解决了Test package tests; //三只 ...

  7. datasnap中间件如何控制长连接的客户端连接?

    ActiveConnections: TClientDataSet; ... 有客户端连接上来的时候 procedure TForm8.DSServer1Connect(DSConnectEventO ...

  8. Go --- 设计模式(模板模式)

    模版模式真的是一个好东西.所谓模版模式,就是说,某几个类中相同的操作和代码提取到父类的一个函数中,并定义相同的操作为抽象函数.由子类来实现.估计我也没表达清楚,下面还是看代码来讲解吧. 例:我们有两个 ...

  9. 纠结的链接——ln、ln -s、fs.symlink、require

    纠结的链接--ln.ln -s.fs.symlink.require 提交 我的留言 加载中 已留言 inode 我们首先来看看 linux 系统里面的一个重要概念:inode. 我们知道,文件存储在 ...

  10. 【Mongodb教程 第一课 补加课】 Failed to connect to 127.0.0.1:27017, reason: errno:10061 由于目标计算机积极拒绝,无法连接

    1:启动MongoDB 2014-07-25T11:00:48.634+0800 warning: Failed to connect to 127.0.0.1:27017, reason: errn ...