SirRawlins
SirRawlins

Reputation: 494

has_one in a has_many

I have an association I'm struggling with. I have a Department model, which can have many staff members, one of which is the manager.

I need to be able to call.

Department.staff - and get a collection of all staff including the manager. Department.manager - and get the manager.

User.department - and get the users department, whether they are staff or manager. User.is_manager - and get a boolean as to whether they manage a department or not. User.manages - get the department they manage.

What is the best of setting up this association? I have currently started with something like this:

class User < ActiveRecord::Base
      belongs_to :department
      has_one :manages, :class_name => 'Department', :foreign_key => :manager_id
end

class Department < ActiveRecord::Base
      belongs_to :manager, :class_name => "User"
      has_many :staff, :class_name 'Users'
end

The problem that I have with this, is that I have to add the manager both as the manager and as a member of staff, which feels a little clumbsy - but perhaps I'm being picky?

Can anyone suggest some better options?

Upvotes: 0

Views: 143

Answers (1)

Thanh
Thanh

Reputation: 8604

Try this association:

class Department < ActiveRecord::Base
  has_many :staffs, class_name: "User"
  has_one :manager, class_name: "User", foreign_key: "manager_id"
end

class User < ActiveRecord::Base
  belongs_to :department
end

Make sure your User table has a column called manager_id, and a column called department_id. If you have a boolean column called manager in your User table, you will have a method manager? to check whether user is manager or not.

To do what you want:

@department = Department.find(1) # Find department with id = 1
@department.staffs # Get all staffs of department

@department.manager.name # Get name of manager of department

@user = User.find(1) # Find user with id = 1
@user.department.name # Get name of department which user belongs to
@user.manager? # Return value of manager column

Upvotes: 1

Related Questions