Ali
Ali

Reputation: 5476

Rails: Handling data not found from database

This is probably one of the most basic questions out there but I still thought stackoverflow would be the best way for me to get the logic right.

My simple question is, how do you handle the database query if it does not return anything. Here is my code below;

@tokenSelected=Token.where(:tokenCode => "ABCDRRREF").first

And later on when I want to check if the @userSelected.userID is empty, it gives me the error;

<h1>
  NoMethodError
    in InitsController#create
</h1>
<pre>undefined method `empty?&#x27; for nil:NilClass</pre>

What can I do to prevent that

Upvotes: 0

Views: 179

Answers (2)

Amit Patel
Amit Patel

Reputation: 15985

Use object.present? it returns false for nil, [], {}, empty string and empty collection.

Upvotes: 2

Salil
Salil

Reputation: 47472

Instead of empty? use blank?

   @tokenSelected.blank?

An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank.

Upvotes: 2

Related Questions