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

I found this cool little snippet of code somewhere on the internet. Anywhere you access an object in a view, adding the following will ensure the page doesn’t blow up:

 <%= @object.association.variable rescue nil %>

Of course, you won’t know if you have an error now either.

6 thoughts on “You have a nil object when you didn’t expect it!

  1. Mohit

    On Line number 5 it is showing the following error
    NoMethodError in Admin#admin
    Showing app/views/admin/admin.rhtml where line #5 raised:

    You have a nil object when you didn’t expect it!
    You might have expected an instance of Array.
    The error occurred while evaluating nil.each

    Extracted source (around line #5):

    1- Product Listing
    2-
    3-
    <tr valign=”top” class=”ListLine”>

    <img width=”60″ height=”70″ src=”"/>

    ‘show’, :id => product %>
    ‘Edit’, :id => product %>
    ‘destroy’, :id => product}, :confirm => “Are you Sure??” %>

    @product_pages.current.previous }
    end %>
    @product_pages.current.next }
    end %>

    ‘new’ %>

    Reply
  2. Duke

    Check out this little snippet:
    def carefully(default = nil)
    begin
    yield
    rescue NoMethodError => e
    raise unless e.message["You have a nil object"]
    default
    end
    end

    carefully { @object.association.variable }

    It only rescues when it’s dereferencing a nil, rather than on any error. In view code, and aesthetically, I do sort of prefer yours though.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>