Best way to find a single record using ActiveRecord 3 / Arel?

让人想犯罪 __ 提交于 2019-12-05 08:28:38

问题


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?


回答1:


Rails 4 :

Foo.find_by bar: 'a_value' , wibble: 'a wibble value'



回答2:


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.




回答3:


Rails gives you a whole load of magic methods for this kind of thing:

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:

Foo.find_by_bar!('a-value')



回答4:


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' })


来源:https://stackoverflow.com/questions/6326440/best-way-to-find-a-single-record-using-activerecord-3-arel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!