Last Updated: February 25, 2016
· chrishale

Ruby on Rails - no method error when association is nil

This is something i got really flummoxed with in my first few months of building with ruby on rails. If i had the following code;

<%= article.user.name %>

And the user had been deleted, i would get a no method error. As the user would be nil and there isn't a 'name' method for nil. For a while i found my self writing;

<%= article.user.present? ? article.user.name : "Unknown User" %>

But it gets tedious if you are wanting to chain a few associations e.g.

<% if article.user.present? %>
   <% if article.user.location.present? %>
      <%= article.user.location.title %>
   <% end %>
<% end %>

Even with short hand it becomes a ball ache. So what I do now is;

<%= "#{article.user.name}, #{article.user.location.title}" rescue "Unknown User" %>

Obviously if you've written some bad code elsewhere it could throw an exception and your left with "Unknown User", but with proper unit tests - that shouldn't be a problem, eh?

Say Thanks

1 Response
Add your response

0 w1fpi2ngr0efg5xqwa7 i7ngmxyol5vqwbr imf2qserm3cnlz0rsapgbapq cn4erdg2djl 3j2

Great solution to minimize the code. Thanks!

over 1 year ago ·