简体   繁体   English

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

[英].find or where condition in active record querying

I am confused on where to use '.find' and where to use 'where'. 我对在哪里使用“ .find”和在哪里使用“ where”感到困惑。 is there a difference in the performance during the execution of the query ?? 查询执行期间的性能有何不同?

example : converted the existing queries which are using .find as below : 示例:转换使用.find的现有查询,如下所示:

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

FileOrFolder.where(fullpath: completePath).select(:id).first

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

Component.where(cluster_id: cluster_id, name: key).first

These are all equivalent. 这些都是等效的。 What you're seeing here is the evolution of the ActiveRecord query syntax from before AREL was incorporated. 您在这里看到的是ActiveRecord查询语法在合并AREL之前的演变。 The older style dynamic finders are still valid, though. 不过,较早版本的动态查找器仍然有效。

This syntax is from ROR 2.x and earlier using dynamic finders: 此语法来自ROR 2.x及更早版本,使用动态查找器:

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

Whereas these are more in the ROR 3.x style: 而这些在ROR 3.x样式中更多:

FileOrFolder.where(fullpath: completePath).select(:id).first
Component.where(cluster_id: cluster_id, name: key).first

And your last example using find is valid in either context. 您使用find的最后一个示例在两种情况下均有效。

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

When in doubt, consult the ROR query guide . 如有疑问, 请查阅ROR查询指南

I personally find the where styles are very useful when you're building up a query over several lines of code and not all at once. 当您通过几行代码而不是一次全部构建查询时where我个人发现样式非常有用。 Since they defer execution until the latest moment, they let you build the query piecemeal. 由于他们将执行推迟到了最新时刻,因此您可以逐步构建查询。

It doesn't make a significant performance difference because usually they will both generate the same SQL, eg: 并没有明显的性能差异,因为通常它们都将生成相同的SQL,例如:

Article.find_by_headline('foo')
=> SELECT `articles`.* FROM `articles` WHERE `articles`.`headline` = 'foo' LIMIT 1

Article.where(headline: 'foo').first
=> SELECT `articles`.* FROM `articles` WHERE `articles`.`headline` = 'foo' LIMIT 1

你应该更喜欢where的风格前进,轨道4,5已否决使用find_by_ -见http://edgeguides.rubyonrails.org/4_0_release_notes.html#active-record-deprecations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM