Nick Coelius
Nick Coelius

Reputation: 4746

Ruby on Rails 'find' and its return value

Should be an easy question, but I couldn't find anything on SO about it, so I'm just throwing mine out there:

thing_i_use = Thing.find(params[:id])

As it stands, in the event that there is no Thing with params[:id], the website defaults to a development page with stack tracing, etc., claiming that there is no thing with ID=etc.

What I'm wondering is how to test against this such that thing_i_use is nil if the params[:id] doesn't exist, or is the object itself. Basically, using the non-existence of the object in my logic later on in the code.

Upvotes: 4

Views: 6060

Answers (3)

krohrbaugh
krohrbaugh

Reputation: 1320

If you want nil returned if the object with that ID doesn't exist, you can use:

thing = Thing.find_by_id(params[:id])

If you want to test if it exists (and get true/false):

Thing.exists?(params[:id])

Upvotes: 4

apneadiving
apneadiving

Reputation: 115521

Replace:

thing_i_use = Thing.find(params[:id])

With:

thing_i_use = Thing.find_by_id(params[:id])

The latest won't spit any error if id doesn't exist or is nil.

thing_i_use will only be nil, this will be the only test to do.

Upvotes: 8

glortho
glortho

Reputation: 13200

thing_i_use = Thing.find(params[:id]) rescue nil

Upvotes: 0

Related Questions