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.

 

Tags: , , , ,

6 Responses to “You have a nil object when you didn’t expect it!”

  1. Mohit Says:

    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’ %>

  2. Duke Says:

    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.

  3. Timur Alhimenkov Says:

    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

  4. Randy Says:

    Timur,

    Sure you can take a snippet as long as you give credit back to here :)

  5. arommaden Says:

    Hello. Your site displays incorrectly in Opera, but content excellent! Thanks for your wise words =)

  6. Neixertem Says:

    ?????????? ????. ???? ????? ? ????? ???????

    ????? ????? ?? gamebulletin.ru

Leave a Reply