conditional logic when dealing with nil

0 views
Skip to first unread message

Josh

unread,
Jul 17, 2007, 6:38:33 PM7/17/07
to Ruby on Rails: Talk
I had a piece of code in an rjs file that checked to see if a variable
existed:

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

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 ...
end

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?

Chris

unread,
Jul 17, 2007, 7:13:51 PM7/17/07
to Ruby on Rails: Talk
Try this:
if @product && @product.price.blank?
# Do something here
end

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.

Chris

On Jul 18, 8:38 am, Josh <jjkie...@gmail.com> wrote:
> I had a piece of code in an rjs file that checked to see if a variable
> existed:
>
> if @product
> ... do something here ...
> end
>
> 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?

Reply all
Reply to author
Forward
0 new messages