Topic: how to check for null value

how do i check for a null value?

    <% if ingredient.name.empty? then %>
      <% puts "nothing here!!!" %>
    <% else %>
      (<%=h ingredient.time %> minutes) with <%=h ingredient.tool %>
    <% end %>

i'm getting

You have a nil object when you didn't expect it!

i'm sure this is an easy one but i have been looking for a while with no help so far.

thanks in advance.

Re: how to check for null value

Hi Kuliksco,

I'm pretty new at ruby/rails so I'll just try to give an answer ( however, I'm getting a similar error). From other posts/articles/tutorials I've seen the use of nil instead of empty.

For example, instead of:

ingredient.name.empty?

Try:

ingredient.name.nil?

Hope it helps or at least points you in the right direction! If it doesn't I'm guessing you can't call methods on database columns? (My terminology might be off)

Re: how to check for null value

yea i actually tried to use .nil? but that actually returned saying that i was evaluating a nil value as well tongue

Re: how to check for null value

Actually, using .nil? or .empty? should work just fine if name is an attribute of the Ingredient class. Even if it isn't, you would get an 'undefined method 'name' for #<Ingredient...

It appears to me that your ingredient is the nil value here, not its name. So you can't evaluate if the name is nil, empty, or otherwise.

To test if this is the case, try just printing the ingredient name or any other attribute of the ingredient. I would suggest running some tests from the console to debug this more quickly.

"Yeah, well, you know, that's just, like, your opinion, man." -El Duderino

http://jerodsanto.net

Re: how to check for null value

Kuliksco,

Checkout my post (which I was able to solve thanks to your code's "empty" method).

http://railsforum.com/viewtopic.php?id=18290

I was have the exact same problem you were. Make sure your relationships are correct (if you have them) in the model and also make sure if it's a belong_to make sure the instance is singular and if it's a has_many it is plural. That was giving me a hard time (and causing similar errors).

Re: how to check for null value

always use .blank? ... it's a feature of rails that will always use the according check no matter if you call it on a string, array, hash or whatever ...

Re: how to check for null value

great thanks!! blank? worked.

Re: how to check for null value

Duplex,

Thanks for the heads up on the .blank? method. This will be a life saver!

Re: how to check for null value

Duplex wrote:

always use .blank? ... it's a feature of rails that will always use the according check no matter if you call it on a string, array, hash or whatever ...

I joined just so I could say, Thank you!

Last edited by PicklePumpers (2010-09-17 10:40:30)

Re: how to check for null value

Awesome!