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.

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

  1. 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
    <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 %> }
    end %>

    ‘new’ %>

  2. Check out this little snippet:
    def carefully(default = nil)
    rescue NoMethodError => e
    raise unless e.message[“You have a nil object”]

    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.

  3. Wow! Thank you very much!
    I always wanted to write in my blog something like that. Can I take part of your post to my blog?
    Of course, I will add backlink?

    Regards, Your Reader

Leave a Reply

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