1

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.

Community
  • 1
  • 1
Noz
  • 6,216
  • 3
  • 47
  • 82

2 Answers2

0

To throw the 404 error, it needs to be

Upload.find_by_id!(params[:id])

The exclamation point is the magic.

kayluhb
  • 648
  • 7
  • 21
  • 3
    This doesn't really answer the original question, so I can't upvote, but it did answer my own question that led me here - "How do I get `find_by_id` to raise?". Thanks – Nick Mar 27 '14 at 15:55
  • @Nick haha. What was the original question? Just looked back at it and I don't really see one... – kayluhb Mar 27 '14 at 16:17
  • I think he's trying to ask why he was getting an exception with `find_by_id` since it should not raise. – Nick Mar 27 '14 at 18:13
0

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.

Noz
  • 6,216
  • 3
  • 47
  • 82