John
John

Reputation: 3460

Rails prevent error when ActiveRecord association is nil

I have a table like "groups" that stores a list of groups that my "users" can belong to. In the User model, this is accomplished with belongs_to :group. In my view, I want to display the group name. I'm trying to do that with @user.group.name.

The problem is that not every user is assigned to a group, so @user.group for example would be nil. So, I get a NoMethodError: undefined method 'name' for nil:NilClass which is frustrating.

What is the best way to work around this problem?

Upvotes: 1

Views: 2024

Answers (3)

Nick Colgan
Nick Colgan

Reputation: 5508

The simplest way would be to do something like this:

<% if @user.group.present? %>
  <%= @user.group.name %>
 <% end %>

However, according to the Law of Demeter, a model should only talk to it's immediate association/should not know about its association's methods.

So, ideally, you should do something like this (in your User model):

delegate :name, :to => :group, :prefix => true, :allow_nil => true

Which you can then access through @user.group_name. It will return nil if there is no associated group, but will not raise an exception. This is equivalent to

def group_name
  group.try(:name)
end

Upvotes: 4

MurifoX
MurifoX

Reputation: 15089

I would create a method with a good name, so it would be easy to reuse the code.

def is_assigned?
  self.group
end

<% if @user.is_assigned? %>
  ...
<% end %>

Upvotes: 0

x1a4
x1a4

Reputation: 19485

I typically use Object#try for this:

@user.group.try(:name) # returns nil if @user.group is nil

Upvotes: 4

Related Questions