Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
Nick Coelius Avatar asked Oct 14 '25 17:10

Nick Coelius


2 Answers

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.

like image 80
apneadiving Avatar answered Oct 17 '25 07:10

apneadiving


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])
like image 41
krohrbaugh Avatar answered Oct 17 '25 08:10

krohrbaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!