.find或活动记录查询中的条件

Vin*_*nay 1 ruby activerecord ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我很困惑在哪里使用'.find'以及在哪里使用'where'.查询执行期间的性能是否存在差异?

示例:转换使用.find的现有查询,如下所示:

FileOrFolder.find_by_fullpath(completePath, :select=>"id") - >

FileOrFolder.where(fullpath: completePath).select(:id).first
Run Code Online (Sandbox Code Playgroud)

Component.find(:first, :conditions=>["cluster_id = ? AND name = ?", cluster_id, key]) - >

Component.where(cluster_id: cluster_id, name: key).first
Run Code Online (Sandbox Code Playgroud)

Dav*_* S. 8

这些都是等价的.你在这里看到的是从结合AREL之前的ActiveRecord查询语法的演变.不过,旧式动态查找器仍然有效.

此语法来自ROR 2.x及更早版本,使用动态查找器:

FileOrFolder.find_by_fullpath(completePath, :select=>"id")
Run Code Online (Sandbox Code Playgroud)

而这些更多的是ROR 3.x风格:

FileOrFolder.where(fullpath: completePath).select(:id).first
Component.where(cluster_id: cluster_id, name: key).first
Run Code Online (Sandbox Code Playgroud)

您使用的最后一个示例find在上下文中都有效.

Component.find(:first, :conditions=>["cluster_id = ? AND name = ?", cluster_id, key])
Run Code Online (Sandbox Code Playgroud)

如有疑问,请参阅ROR查询指南.

我个人发现where当你在多行代码上构建查询时,这些样式非常有用,而不是一次完成.由于他们将执行推迟到最新时刻,因此他们允许您逐步构建查询.