Developer's Blog

Using Rescue Statement When Outputting Data in ERB

Posted May 26, 2009 by Justin Lewis. Filed under Code.

Sometimes when you’re writing ERB, you’ll have to output something like this:

<%= article.category.name %>

But if the category is not set, you’ll probably get an error page with a nasty backtrace of an exception, along with an error like:

undefined method 'name' for nilclass

There are a couple ways to avoid this. First, you can test if category is nil before outputting the value:

<% if not article.category.blank? -%>
<%= article.category.name %>
<% else -%>
No Category
<% end -%>

Another way that is a bit cleaner is to add a rescue statement to the end of your output:

<%= article.category.name rescue 'No Category' %>

Using rescue will only catch exceptions, and will not test if the name itself is nil or an empty string. So, use either one based on your situation.

Comments

  • There are no comments for this post.

Leave a Comment

You must have JavaScript enabled to leave comments.