Tobi89
Tobi89

Reputation: 199

ruby-on-rails check if query result is empty (Model.find)

i´m using ruby on rails and trying to check if a query is returning a value or not.

This is the query:

@search = Customer.find_by_name($login_name)

If the query finds a result, everything is fine, but how can i react on empty results?

I tried:

if @search.empty?
  flash[:notice] = 'Username nicht bekannt'
  redirect_to :action => :login
end

But i get an error:

undefined method `empty?' for nil:NilClass

Any Ideas what went wrong?

Thank you!!!

Upvotes: 10

Views: 28121

Answers (2)

Rahul garg
Rahul garg

Reputation: 9362

Use this to check for nil as well as empty cases:

@search.blank?

For the opposite case (NOT nil and NOT empty), use .present?:

@search.present? #equivalent of [email protected]?

The reason your query returned nil instead of empty is :

Customer.find_by_name($login_name)

always returns one result of object Customer or nil if there is no such result,

while something like:

Customer.where(:name=>$login_name)

will return you ActiveRecord::Relation (which can have 0-n results) always. and empty? method will work on it

Upvotes: 32

Fiona T
Fiona T

Reputation: 1929

If no result is found, find_by_name returns a nil object, rather than an empty array. To check whether a customer was found, you can use if @search.nil? or simply if !@search or unless @search, since nil is falsy in ruby.

@search = Customer.find_by_name($login_name)
unless @search
  flash[:notice] = 'Username nicht bekannt'
  redirect_to :action => :login
end

Upvotes: 2

Related Questions