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

25,230

Solution 1

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

Solution 2

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
Share:
25,230
Tobi89
Author by

Tobi89

Updated on July 09, 2022

Comments

  • Tobi89
    Tobi89 almost 2 years

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