Ruby-on-rails Rails .where 与 .find
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9574659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails .where vs .find
提问by AdamB
I've noticed that the Model.wheremethod always returns an array even if there is only one result where as the Model.findmethod doesn't. Is there any reason for this? I thought Model.wherewas the preferred function since Rails 3.X.
我注意到该Model.where方法总是返回一个数组,即使只有一个结果,而该Model.find方法没有。这有什么原因吗?我认为这Model.where是自 Rails 3.X 以来的首选功能。
Should I be using Model.findwhen I expect a single result and Model.wherewhen I expect more than one result?
我应该Model.find在期望单一结果Model.where时还是期望多个结果时使用?
回答by Andrew Marshall
wherereturns anActiveRecord::Relation(not an array, even though it behaves much like one), which is a collectionof model objects. If nothing matches the conditions, it simply returns an empty relation.find(and its related dynamicfind_by_columnnamemethods) returns a singlemodel object. If nothing is found, anActiveRecord::RecordNotFoundexception is raised (but not with the dynamicfind_by_methods).While
findcan return an Array of records—not a Relation—if given a list of IDs, usingwhereis preferred since Rails 3. Many similar uses offindare now deprecated or gone entirely.
where返回一个ActiveRecord::Relation(不是数组,即使它的行为很像一个),它是模型对象的集合。如果没有匹配条件,它只是返回一个空关系。find(及其相关的动态find_by_columnname方法)返回单个模型对象。如果未找到任何内容,ActiveRecord::RecordNotFound则会引发异常(但不是使用动态find_by_方法)。虽然
find可以返回一个记录数组——而不是一个关系——如果给定一个 ID 列表,where从 Rails 3 开始使用是首选。 许多类似的用法find现在已被弃用或完全消失。
So yes, if you only want and expect a single object, using findis easier, as otherwise you must call Model.where.first.
所以是的,如果你只想要一个对象,使用find更容易,否则你必须调用Model.where.first.
Note that old-style hash options to findand many dynamic find_methods are deprecated as of Rails 4.0 (see relevant release notes).
请注意,从 Rails 4.0 开始,旧式哈希选项find和许多动态find_方法已被弃用(请参阅相关发行说明)。
回答by Kamil Lelonek
回答by iltempo
Model.findis using the primary key column. Therefore there is always exactly one or no result. Use it when you are looking for one specific element identified by it's id.
Model.find正在使用主键列。因此,总是只有一个结果或没有结果。当您在寻找由其 id 标识的特定元素时使用它。

