Ruby-on-rails 使用 ActiveRecord 3 / Arel 查找单个记录的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6326440/
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
Best way to find a single record using ActiveRecord 3 / Arel?
提问by John Bachir
Where I used to do this:
我曾经这样做的地方:
Foo.find_by_bar('a-value')
I can now do this:
我现在可以这样做:
Foo.where(:bar => 'a-value').limit(1).first
Is this recommended? Is this the best way? Should I continue to use the "old" way because it continues to be useful syntactic sugar, or is there an Even Better way I can do that now, which will support chaining and all the other good stuff?
这是推荐的吗?这是最好的方法吗?我应该继续使用“旧”方式,因为它仍然是有用的语法糖,还是有更好的方式我现在可以做到这一点,它将支持链接和所有其他好东西?
回答by SureshCS
Rails 4 :
轨道 4 :
Foo.find_by bar: 'a_value' , wibble: 'a wibble value'
回答by nmunson
I think the preferable way to return a single record would be along the lines of your second example, but you can omit the limit part:
我认为返回单个记录的更好方法是按照第二个示例的方式,但您可以省略限制部分:
Foo.where(:bar => 'a-value').first
This follows the new syntax and supports chaining if you want to add more conditions to the lookup.
如果您想向查找添加更多条件,这遵循新语法并支持链接。
回答by Will Tomlins
Rails gives you a whole load of magic methods for this kind of thing:
Rails 为这种事情提供了大量的魔法方法:
Foo.find_by_bar('a-value')
You can also use multiple attributes:
您还可以使用多个属性:
Foo.find_by_bar_and_wibble('a foo value', 'a wibble value')
And appending a ! causes it to throw a RecordNotFound if nothing's found:
并附加一个!如果未找到任何内容,则会导致它抛出 RecordNotFound:
Foo.find_by_bar!('a-value')
回答by Victor Lellis
Other alternative:
其他选择:
Foo.find(:first, conditions: { bar: 'a-value' })
You can also use multiple attributes:
您还可以使用多个属性:
Foo.find(:first, conditions: { bar: 'a-value' , wibble: 'a wibble value' })

