问题描述
当我调用找到一个ID,就变成了有针对性的查找,将抛出一个错误RecordNotFound。
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
和,如果没有找到,我希望它提高RecordNotFound错误。这是可能的呢?或者我应该简单地增加一些code对证零?如果零?提高自己的错误?如果是这样,我怎么做,在Rails 3的?
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?
推荐答案
您最后一款是你需要做的。无论是对证零,或提高自己的异常。为了提高自己的异常,请执行以下操作:
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)
这篇关于如何发出'发现'或',其中'引发一个RecordNotFound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!