【问题标题】:How to setup a polymorphic association of People and Users?如何建立人和用户的多态关联?
【发布时间】:2011-12-09 21:09:15
【问题描述】:

如果有 People 模型,如何设置用户和客户的多态关联?

例如,Person 可以充当用户或客户。人们可以是用户(额外的列:用户名、密码),也可以是客户(没有额外的列)。

我正在尝试这样设置

  1. 我不会有单独的用户表和客户表
  2. 我不希望 People 表中包含大量空的用户名和密码列

【问题讨论】:

    标签: ruby-on-rails ruby associations models


    【解决方案1】:

    我同意 moo-juice,正确的方法是人 + 角色。这是一个具体的例子:

    class Person < ActiveRecord::Base
      has_many :roles, :through => :roles_people
      #columns would be username, password, etc
    end
    
    class Role < ActiveRecord::Base
      has_many :people, :through > :roles_people
      #a column of role_type would be required here and the values of such would be Customer, User, etc.  in this class you will put logic that is needed to execute the functions of the role
    end
    
    class RolesPerson < ActiveRecord::Base
       belongs_to :person
       belongs_to :role
       #this is a join model for a many-to-many relationship. you can store info in here about when a person acquired a certain role, etc.
    end
    

    【讨论】:

    • 所以你说我应该添加一个 Roles 表,其中包含 role_type 列;在 People 表中添加角色列;并为 People 表留下一堆用户名和密码列为空? RolesPerson 类有什么作用?
    • @leonel,他建议的 RolesPerson 类,将人们与他们的角色联系起来(允许他们拥有多个角色)。在我看来,拥有大量空的用户名/密码列没什么大不了的。事实上,如果您希望客户登录怎么办?您可以通过具有“登录”角色的方式使用建议的模型来执行此操作(也允许您停用不良客户!)。
    • 好的。我将如何设置帐户管理员?如果每个帐户只能有一个帐户管理员和people belong to account
    • @leonel people 表中不会有任何角色列。 Person 和 Role 之间的多对多关系需要 RolesPerson - 这是它的唯一目的。
    • 理想情况下,person 模型只包含人口统计信息,例如密码、用户名等
    【解决方案2】:

    我会在一个单独的表上使用一个包含空用户名/密码列的表。我将介绍一个名为roles 或类似名称的附加表,以及另一个将人们与他们的身份(用户、客户甚至两者)联系起来的链接表。

    我这样说是因为您不想要两个表并且您不想要额外的列。你必须选择其中之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多