Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 346
Tobi89 Avatar asked Dec 09 '12 18:12

Tobi89


2 Answers

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

like image 177
Rahul garg Avatar answered Oct 21 '22 16:10

Rahul garg


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
like image 31
Fiona T Avatar answered Oct 21 '22 18:10

Fiona T