Michael
Michael

Reputation: 3628

ActiveRecord Relationships : undefined method for nil:NilClass

Consider the following:

class Manager < ActiveRecord::Base
  has_many :employees
end
class Employee < ActiveRecord::Base
  belongs_to :manager
end


employee = Employee.first
puts employee.manager.name

If for some reason an employee does not have a manager I get this:

undefined method `name' for nil:NilClass

Which makes sense. However, is there a clean/suggested way to handle this, so I don't always have to check and see if an employee actually has a manager before I ask for the manager's name?

Upvotes: 2

Views: 2310

Answers (4)

spike
spike

Reputation: 10004

Don't try to be too clever. If you're going to use this repeatedly, make it a function.

class Employee
   def manager_name
     manager.try(:name).to_s # force empty string for nil        
   end
end

Upvotes: 2

nzifnab
nzifnab

Reputation: 16092

I tend to prefer puts employee.manager.try(:name)

The try method returns nil if it was called on nil, but will execute the method properly if manager wasn't nil.

If you want default text:

puts employee.manager.try(:name) || "No Manager"

Upvotes: 0

Whit Kemmey
Whit Kemmey

Reputation: 2230

Try:

puts employee.manager.name unless employee.manager.nil?

Or:

puts (employee.manager.nil? ? "No manager" : employee.manager.name)

Which is equivalent in this case to:

puts (employee.manager ? employee.manager.name : "No manager")

(Equivalent as long as employee.manager can't return false.)

Upvotes: 4

Andy Hayden
Andy Hayden

Reputation: 375375

You can check using the has_attribute? method:

employee.has_attribute? :manager

So something like:

puts employee.manager.name if employee.has_attribute? :manager

Upvotes: 0

Related Questions