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 中,其定义如下:
Run Code Online (Sandbox Code Playgroud)def find_by(*args) where(*args).take end
因此,
take
与first
您的记录顺序不同。first
将根据主键的顺序返回第一条记录,而take
只会返回数据库首先吐出的任何内容。因此,虽然使用
where().take
相当于find_by
并且选择是否使用另一个是一个品味问题,where().first
区别于find_by
微妙而不那么明显的方式。
两者都会产生相同的查询。
根据最新信息,在 Rails 3.1 下,传入 :conditions 将被弃用。
因此,现在执行查询的最佳方法是使用:
Class.where(:type => 4).first
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8507 次 |
最近记录: |