当前位置: 动力学知识库 > 问答 > 编程问答 >

activerecord - 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 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)

分享给朋友:
您可能感兴趣的文章:
随机阅读: