How to issue a 'find' or 'where' that raises a RecordNotFound

爱⌒轻易说出口 提交于 2019-12-12 10:37:14

问题


When I call a find with an id, it becomes a targeted find, and will throw an error RecordNotFound.

Foo::Bar.find(123) # RecordNotFound if no Bar with id 123 exists.

But when I call that with conditions, I get nil if not found:

Foo::Bar.find(:first, :conditions => [ "lower(name) = ?", name.downcase ])

I want such a conditional search to raise an error too. I know I can do:

Foo::Bar.find_by_name!("CocktailBar") #=> raises Recordnotfount if not not found.

But that has only really simple conditions. Mine need a little more complexity; actually something like:

Foo.Bar.select{ |pm| pm.name.downcase =~ /cocktail/}.first

And, if nothing is found, I want it to raise the RecordNotFound error. Is that possible at all? Or should I simply add some code to check against nil? and if nil? raise the error myself? And if so, how do I do that in Rails 3?


回答1:


Your final paragraph is what you need to do. Either check against nil, or raise the exceptions yourself. To raise the exception yourself, do the following:

Foo::Bar.find(:first, :conditions => [ "lower(name) = ?", name.downcase ]) || raise(ActiveRecord::RecordNotFound)



回答2:


In the last snippet of code you are actually fetching all records from DB and then doing select on a Ruby array. It has nothing to do with ActiveRecord, so you can do whatever you like to raise exception manually, either use the code suggested by Douglas, or if, or unless etc. But it seems that you don't quite understand what your code does. Your select {...} is not translated into SQL SELECT ... WHERE(...).

If you need an exception raised automatically by ActiveRecord query, use this:

Foo::Bar.where([ "lower(name) = ?", name.downcase ]).first!

The equivalent bang methods exist for find_by methods as well, for example Foo::Bar.find_by_name!(name)



来源:https://stackoverflow.com/questions/9616946/how-to-issue-a-find-or-where-that-raises-a-recordnotfound

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