Topic: Best way to deal with nil objects in views...

"NoMethodError in Articles#suggested...
You have a nil object when you didn't expect it!"

Isn't too pretty.  I can certainly check before iterating through a set of objects in the view itself, but it seems to me the template shouldn't have to deal with this sort of situation.

It would be nice to have the template fail gracefully when @articles is nil.

<% for article in @articles %>

Is there a better way to protect the views from these sorts of errors?

Re: Best way to deal with nil objects in views...

How are you generating the @articles instance variable? If you use an empty array instead of nil it will not produce an error.

Railscasts - Free Ruby on Rails Screencasts

Re: Best way to deal with nil objects in views...

or you could just add the following to the end of the loop:

<% end unless @articles.blank? %>

--jake

---------------------------------------------------------------------
Rails Development - Agile rails consulting and development for startups on a budget
Flvorful Blog - Some ramblings
Flvorful's Open Source Projects - Some handy hacks for your rails projects.

Re: Best way to deal with nil objects in views...

Ok. great.  This helps a lot.