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!!!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With