0

我有一个正在与之斗争的协会。我有一个部门模型,它可以有很多员工,其中一位是经理。

我需要能够打电话。

Department.staff - 并获取包括经理在内的所有员工的集合。Department.manager - 并获得经理。

User.department - 并获取用户部门,无论他们是员工还是经理。User.is_manager - 并获得一个关于他们是否管理部门的布尔值。User.manages - 获取他们管理的部门。

成立这个协会最好的办法是什么?我目前已经开始这样的事情:

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

我遇到的问题是,我必须将经理添加为经理和员工,这感觉有点笨拙 - 但也许我很挑剔?

谁能建议一些更好的选择?

4

1 回答 1

1

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
于 2012-12-03T21:03:22.450 回答