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.

June 7th, 2008 at 12:20 pm
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’ %>
December 31st, 2008 at 12:51 am
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.