Last Updated: February 25, 2016
·
2.702K
· 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?

1 Response
Add your response

Great solution to minimize the code. Thanks!

over 1 year ago ·