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:
For the opposite case (NOT nil and NOT empty), use .present?:
The reason your query returned
nilinstead ofemptyis :always returns one result of object
Customerornilif there is no such result,while something like:
will return you
ActiveRecord::Relation(which can have 0-n results) always. andempty?method will work on it