【发布时间】:2011-12-09 21:09:15
【问题描述】:
如果有 People 模型,如何设置用户和客户的多态关联?
例如,Person 可以充当用户或客户。人们可以是用户(额外的列:用户名、密码),也可以是客户(没有额外的列)。
我正在尝试这样设置
- 我不会有单独的用户表和客户表
- 我不希望 People 表中包含大量空的用户名和密码列
【问题讨论】:
标签: ruby-on-rails ruby associations models
如果有 People 模型,如何设置用户和客户的多态关联?
例如,Person 可以充当用户或客户。人们可以是用户(额外的列:用户名、密码),也可以是客户(没有额外的列)。
我正在尝试这样设置
【问题讨论】:
标签: ruby-on-rails ruby associations models
我同意 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
【讨论】:
people belong to account
我会在一个单独的表上使用一个包含空用户名/密码列的表。我将介绍一个名为roles 或类似名称的附加表,以及另一个将人们与他们的身份(用户、客户甚至两者)联系起来的链接表。
我这样说是因为您不想要两个表并且您不想要额外的列。你必须选择其中之一。
【讨论】: