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

12

我想知道哪种方法可以最快地返回一条记录。

Class.where(:type => 4).first
Class.find(:first, :conditions => ["type = ?", 4])

执行过程完全相同吗?

2个回答

16

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

Class.find_by(type: 4)

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

This method has been added on Rails 4 and it is defined like this:

def find_by(*args)
 where(*args).take
end

So, take differs from first in regards to the order of your records. first will return the first record according to the order of the primary key while take will just return whatever the database spits out first.

So while using where().take is equivalent to find_by and choosing whether to use one of the other is a matter of taste, where().first differs from find_by in a subtle and not so obvious way.


6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接