开发者

In Ruby on Rails, is there a way to say, try Product.find(12345) but don't error if not found?

For example, just have it return nil if not found, or must we always use begin... rescue... end 开发者_JS百科to catch the exception?


You can use

Product.find_by_id(12345)

. This would return nil and not error.

Thanks....


You can use rescue_from to specify a method to use to handle the exception. If it's something that's used in multiple places this will help remove duplication. You could even put it in your application controller if it's used across controllers. Here are some examples: http://m.onkey.org/rescue-from-dispatching


You could test it first with Product.exists?(12345)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜