Reputation: 4746
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
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
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