简体   繁体   中英

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?

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

我通常为此使用Object#try

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

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM