Rails 2: Model.find(1) gives ActiveRecord error when id 1 does not exist

后端 未结 8 1467
無奈伤痛
無奈伤痛 2020-11-28 12:03

I am using Rails 2.3.5 and in that if I give Model.find(1) and if 1 is not in the database, it returns ActiveRecord error. Should it just be returning nil

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 12:33

    If you want the exception to be thrown in find_by_attributes flavors of the finder methods, you can use the bang! version of the method.

    For example,

    Model.find_by_category!(a_category_value)
    

    will throw RecordNotFound if no match is found.

    I found this to be DRY in scenarios like RESTful controllers, where I have a common error handler for the exception and I want my actions to behave consistently when a resource matching the given parameters is not found.

提交回复
热议问题