经理 -> rails 中的一级员工协会

Manager -> Employee association one level in rails

我想创建经理->员工协会。

如何实现这个设计? 我创建了一些更接近的东西(代码在下面)但是在我的设计经理中可以有其他经理。

class User < ApplicationRecord
  has_many :employee, class_name: "User", foreign_key: "manager_id"
  belongs_to :manager, class_name: "User", foreign_key: "manager_id"
end

非常感谢任何帮助!

我认为你的 table 中多一个字段 manager: boolean 会更好。在此字段的基础上,您可以决定用户是否是管理员。如果经理字段为真,您还可以添加 manager_id 必须为空的验证。

validate :manager_id_blank_for_manager

has_many :employees, class_name: "User", foreign_key: "manager_id", dependent: :restrict_with_exception

scope :managers, ->{ where(manager: true) }

def manager?
  manager
end

private

def manager_id_blank_for_manager
  if manager_id.present? && manager?
    errors.add(:manager_id, :must_be_blank_for_manager) # Move this error to yml file
  end
end

您拥有的是真正标准的自连接设置(有一些小问题)。您可以通过添加自定义验证来限制树的深度:

class User < ApplicationRecord
  # optional: true is needed in Rails 5+ since belongs_to is no
  # longer optional by default
  belongs_to :manager, class_name: 'User',
                       optional: true
  # pay attention to pluralization
  has_many :employees, class_name: 'User',
                       foreign_key: 'manager_id'
  # calls the custom validation we will define later
  validate :manager_must_be_a_manager, unless: :manager?

  def manager?
    manager.nil?
  end

  private
    # our custom validation method
    def manager_must_be_a_manager
      errors.add(:manager, 'is not a manager') unless manager.manager?
    end
end

所以现在如果我们 运行:

user_1 = User.create!
user_2 = User.create!(manager: user_1)
User.create!(manager: user_2)

第三行会加注ActiveRecord::RecordInvalid: Validation failed: Manager is not a manager.