Rails Find_by_id raises exception

余生颓废 提交于 2019-12-24 02:25:08

问题


I was led to believe that the difference between Object.find and Object.find_by_id is that find will raise a RecordNotFound exception whereas find_by_id simply returns nil if nothing is found.

However, in my Rails 3 app if I attempt to search my Uploads model with a bogus id I get:

ActiveRecord::RecordNotFound in UploadsController#show

Couldn't find Upload with id=59

Request

Parameters:

{"id"=>"59"}

Here is the line of code thats messing up:

@upload = Upload.find_by_id(params[:id])

I'm using Rails 3.1.3.


回答1:


To throw the 404 error, it needs to be

Upload.find_by_id!(params[:id])

The exclamation point is the magic.




回答2:


This turned out to be a problem with the Impressionist gem that I'm using as it was hooked into my Upload show action and tried to execute it's own find before I had a chance to deal with it.



来源:https://stackoverflow.com/questions/12148785/rails-find-by-id-raises-exception

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