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?
I typically use Object#try for this: