我想知道哪种方法可以最快地返回一条记录。
Class.where(:type => 4).first
Class.find(:first, :conditions => ["type = ?", 4])
执行过程完全相同吗?
我想知道哪种方法可以最快地返回一条记录。
Class.where(:type => 4).first
Class.find(:first, :conditions => ["type = ?", 4])
执行过程完全相同吗?
如果您不关心顺序,最高效的方法是使用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 fromfirst
in regards to the order of your records.first
will return the first record according to the order of the primary key whiletake
will just return whatever the database spits out first.So while using
where().take
is equivalent tofind_by
and choosing whether to use one of the other is a matter of taste,where().first
differs fromfind_by
in a subtle and not so obvious way.
两种方法都可以生成相同的查询结果。
最新消息显示,在Rails 3.1版本中,传递 :conditions 将被弃用。
因此,目前执行该查询的最佳方式是使用:
Class.where(:type => 4).first