I have two types of users: managers, and employees. I use one User controller for both of them.
What I did was add :manager_id to the user table, and put the following in the user model:
class User < ActiveRecord::Base
has_many :employees, :class_name => 'User', :foreign_key => :manager_id
belongs_to :manager, :class_name => 'User'
Sounds simple enough.
But now I want to define the user type. If an user has a manager, he is an employee. If a user has no manager, he is a manager.
What do I need to add to the model so I reference the user type in my views like such:
<% if current_user.manager? %>
You are a manager.
<% else %>
You are not a manager.
<% end %>
I tried to define the user type in the user.rb model but I’m getting an “undefined method ‘manager?’ for nil:NilClass” error :
def manager?
manager_id.nil?
end
def employee?
!manager?
end
Like Ryan Bigg said, you need to check out the error message a little closer. It isn’t that
manager?doesn’t exist as a method on an instance ofUser, it’s that it doesn’t exist onNil. When there isn’t acurrent_user,current_userreturnsnil, which you then callmanager?on.Try this to avoid this error: