Forum: Ruby on Rails conditional logic when dealing with nil

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
66d1d0df01e4bbb82674a353ea68d6ee?d=identicon&s=25 Josh Kieschnick (jjkiesch)
on 2007-07-18 00:39
(Received via mailing list)
I had a piece of code in an rjs file that checked to see if a variable

if @product
  ... do something here ...

that worked fine, but then I also need to check and see if a column is
empty or nil, so i changed it to this:

if @product || !@product.price.blank?
  ... do something here ...

this always gives me "You have a nil object when you didn't expect
it!" errors

is there a better way of doing this without nesting if statements
inside eachother?
B1112061b921903a0b337e10048798af?d=identicon&s=25 Chris (Guest)
on 2007-07-18 01:14
(Received via mailing list)
Try this:
if @product && @product.price.blank?
  # Do something here

In the code below, if @product is nil, the first condition is false so
the second condition is evaluated. @product.price will fail when
@product is nil.

This topic is locked and can not be replied to.