ruby-on-rails - .where(nil) 和 .all 有什么区别?

标签 ruby-on-rails ruby where

我一直在用

Product.all
但是我看到的很多代码都在使用
Product.where(nil)
填充变量时。这个site有一个我发现使用 where(nil) 的例子。我搜索了文档,发现 where(nil) 替换了 scoped 但无法弄清楚它的作用。

最佳答案

我相信过去是有区别的,但是从 Rails 4 开始就不一样了。这是因为从 Rails 4 .all 返回一个关系,而它用于返回一个数组。所以之前:

Product.all

立即向数据库发起查询以返回所有记录,这些记录将加载到内存中的数组中。基本上,您是在告诉 Rails 您现在需要数据。参见 this question了解更多信息。

Product.where(nil) 

创建一个查询(实际上是一个返回 ActiveRecord:Relationanonymous scope)。

查询只会在您尝试访问它的数据时执行。由于它是一个范围,因此您可以链接其他范围(无需每次访问数据库)并在访问数据时将整个链作为一个查询执行。

在问题中链接的 Justin Weiss 文章中,我们看到这段代码:

def index
  @products = Product.where(nil) # creates an anonymous scope
  @products = @products.status(params[:status]) if params[:status].present?
  @products = @products.location(params[:location]) if params[:location].present?
  @products = @products.starts_with(params[:starts_with]) if params[:starts_with].present?
end

当 index 方法结束并返回数据时,该代码将执行一次数据库调用。

但是如果你把第一行改成:

@products = Product.all

该查询将立即执行。然后添加范围,当索引方法结束时将触发另一个查询。这是更低效的。

编辑

我相信数据库调用实际上会在您第一次尝试访问@products 中的某些数据时发生(而不是在 index 方法结束时)。例如。如果你做了@products.first,那么查询就会执行。

关于ruby-on-rails - .where(nil) 和 .all 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46132062/

相关文章:

html - Ruby On Rails ERB CSS 布局问题

ruby-on-rails - 使用 Roo Gem 在 Rails 中解析 XLS 电子表格

iphone - '惰性符号绑定(bind)失败 : Symbol not found: __OSSwapInt16' on jailbroken iPhone when using gem commands

sql - Oracle SQL 使用 Like 作为通配符

ruby-on-rails - &Proc.new 在方法中的作用是什么?

ruby-on-rails - 如何跳过brakeman扫描过程+Rails的具体方法

ruby-on-rails - 如何获取基本网址(例如,http ://localhost:3000) of my Rails app?

ruby - 如何获取模式匹配目录Ruby中的特定文件

c# - 你可以使用 "where"在 c# 中要求属性吗?

c# - 我可以将泛型方法限制为多个接口(interface)吗?