与多个用户'

时间:2017-06-12 14:47:21

标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-5

我在缠绕这个问题时遇到了一些麻烦。我的目标是建立这样的关系:

  • 公司可以有多个用户(团队成员/员工)
  • 用户可以成为众多公司
  • 的一部分
  • 公司可以拥有不同的用户组(即员工,所有者,顾问和执行
  • 用户可以是多个群组的一部分(即用户A 可以是员工公司1 顾问公司2

基本上,我希望能够展示公司的个人资料并展示他们的所有员工,业主,顾问和高管。同样,我也试图通过他们是员工,所有者,顾问还是执行官来搜索用户。另外,用户可以与许多不同的公司和许多不同的组相关联。

我现在的方法/信念就像拥有这些Rails关系一样:

  • 公司 has_many_belongs_to_many 用户
  • 用户 has_many_belongs_to_many 公司
  • 公司 has_one EmployeeTeam ,通过:用户
  • 公司 has_one OwnerTeam ,通过:用户
  • 公司 has_one AdvisorTeam ,通过:用户
  • 公司 has_one ExecutiveTeam ,通过:用户
  • EmployeeTeam has_many 用户
  • OwnerTeam has_many 用户
  • AdvisorTeam has_many 用户
  • ExecutiveTeam has_many 用户

老实说,我不确定我是否过度复杂,如果这是一种有效的方式,或者即使这种方式有效。我对Rails相当陌生,并且非常感谢任何指导/最佳实践。谢谢!

2 个答案:

答案 0 :(得分:0)

  • 公司has_and_belongs_to_many用户
  • 用户has_and_belongs_to_many公司
  • 用户has_and_belongs_to_many群组
  • Group belongs_to Company
  • 群组has_and_belongs_to_many用户
  • EmployeeTeam是Group
  • 的子类
  • OwnerTeam是Group
  • 的子类
  • AdvisorTeam是Group
  • 的子类
  • ExecutiveTeam是Group
  • 的子类
  • 公司has_one EmployeeTeam
  • 公司has_one OwnerTeam
  • 公司has_one AdvisorTeam
  • 公司has_one ExecutiveTeam
  • 公司has_many员工通过EmployeeTeam,类用户
  • 公司has_many所有者通过OwnerTeam,类用户
  • 公司has_many顾问通过AdvisorTeam,类用户
  • 公司通过ExecutiveTeam,类用户
  • 拥有高管人员

这将为您提供公司的功能:

company.users #all users
company.employees #all users with the group employee team
company.owners #all users with the group owner team
company.advisors #all users with the group advisor team
company.executives #all users with the group executive team

您需要创建公司创建他的组

您需要验证用户是否与未与其公司关联的组关联。

它还允许您为整个组编写代码,并为每个组类型编写特定代码

这也只有5个数据库表

  • 公司
  • 用户
  • companies_users
  • groups_users

答案 1 :(得分:0)

在传统的数据设计方法中,我会考虑与用户和公司一起在联结表中引用组信息。看看

http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

在第2.6章中,您将看到一个经典的多对多结点模型,其中“assemblies_parts”作为联结表。在那里你可以添加第三个关系。所以,你会得到一个“users_companies_groups”联结表。在那里,您可以自由地分配三个域之间的关系。

限制可能会出现问题:您不希望用户在同一家公司的两个不同的组中。这可以通过例如仅将“user_id”和“company_id”作为主键来解决。这样,用户被限制在每个公司只有一次。

[编辑:更正了关于限制的最后声明]