Reputation: 161
I just started learning Rails. I have the following question.
I generated "User" models (table "users") and I want to add relation to manager. Manager is also a User. I want to be able to write:
user.manager # => returns User object
I tried to write it like this:
class User
belongs_to :user, as: :manager
end
But it didn't work. Can you please help me.
Upvotes: 2
Views: 126
Reputation: 7655
If Manager
is referenced by manager_id
field, then:
class User
belongs_to :manager, class_name: 'User'
end
You can also identify subordinates
of the user using has_many
relation:
class User
belongs_to :manager, class_name: 'User'
has_many :subordinates, class_name: 'User', foreign_key: 'manager_id'
end
Upvotes: 3
Reputation: 3803
belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
Try this
Upvotes: 1