如何关联这些模型(用户,公司),其中用户可以是雇主和雇员?

How to associate these models(user, company), where User can be Employer and Employee?

在 Rails 4 上的 Ruby 中,我有这些模型:

def User < ActiveRecord::Base
  has_one :company, dependent: :destroy
end

def Company < ActiveRecord::Base
  belongs_to :user
end

所以现在,我希望作为雇主的用户能够拥有一家公司,而这家公司可以有很多用户(员工)。

当我将用户登录为员工时,我希望能够列出他工作的所有公司。

最好的方法是什么?

我不确定在没有更多信息的情况下能否为您提供完整的工作代码文件,但我认为这是继续进行的最佳方式。

class User < ActiveRecord::Base
  self.table_name = "users"
  #Define shared associations/methods
end

class Employee < User
  has_and_belongs_to_many :companies
  #Employee only associations/methods
end

class Employer < User
  has_one :company
  #Employer only associations/methods
end

class Company < ActiveRecord::Base
  has_and_belongs_to_many :employees
  belongs_to :employer
end

由于两者都继承自同一个 User 模型,因此它们将共享一个 table。由于两个派生模型都只使用 has_x,外键将在另一个 table 中,这意味着它们可以共享一个 table 模式,而不会出现大量空值。

同样,我不确定这是否会自动运行,但我认为这是一个好的开始。另一个优点是,通过像这样隔离代码,您可以根据人员类型独立更改功能(例如,您可以对用户使用通用日志功能,但使其更具体地针对员工和雇主 - 例如包括公司或公司他们绑定到)。


事后我意识到还有另一种方法可以做到这一点。您可以使 User 与 Employee 或 Employer 具有多态关联。然后您将检查用户记录的类型,然后拉出关联并调用该记录(雇员或雇主)上的方法。

我唯一不喜欢这个解决方案的地方是它涉及 3 个 table,据我所知,你可以用 1 个。