在 Rails (ActiveRecord) 中找到第一条记录的最快方法是什么?

Jér*_*Boé 9 activerecord ruby-on-rails ruby-on-rails-3

我想知道哪种方法返回记录最快。

Class.where(:type => 4).first
Class.find(:first, :conditions => ["type = ?", 4])
Run Code Online (Sandbox Code Playgroud)

执行是完全一样的吗?

Fla*_*che 10

假设您不关心顺序,最高效的方法是使用find_by

Class.find_by(type: 4)
Run Code Online (Sandbox Code Playgroud)

来自https://github.com/rubocop-hq/rails-style-guide/issues/76

此方法已添加到 Rails 4 中,其定义如下:

def find_by(*args)
 where(*args).take
end
Run Code Online (Sandbox Code Playgroud)

因此,takefirst您的记录顺序不同。first将根据主键的顺序返回第一条记录,而take只会返回数据库首先吐出的任何内容。

因此,虽然使用where().take相当于find_by并且选择是否使用另一个是一个品味问题,where().first区别于find_by微妙而不那么明显的方式。


Blu*_*ish 6

两者都会产生相同的查询。

根据最新信息,在 Rails 3.1 下,传入 :conditions 将被弃用。

因此,现在执行查询的最佳方法是使用:

Class.where(:type => 4).first
Run Code Online (Sandbox Code Playgroud)