是否应该使用一对一关系、列或其他内容?
虽然我的问题具体是在 Ruby on Rails 中,但我也一般性地问:我有一个用户表,并希望指定一些用户为学生,其他用户为教师。在这种情况下设计架构的最佳方法是什么?
编辑: 虽然我最初接受了 vonconrad 的答案——它符合最初的标准——但我必须根据 nhnb 的反馈重新打开并调整问题。
如果学生和/或教师需要额外的(独特的)属性该怎么办?
Though my problem is specifically in Ruby on Rails, I'm also asking generally: I have a users table and want to designate some users to be students and others to be teachers. What is the best way to design the schema in this case?
Edit:
Though I originally accepted vonconrad's answer--it fits the original criteria--I have to reopen and adjust the question based on feedback from nhnb.
What should be done if students and/or teachers require additional (unique) attributes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这很大程度上取决于教师和学生之间有多少不同的属性,以及添加或删除新的独特属性的频率。如果情况是它们差异很大,您有两种选择:
has_many :user, :polymorphic => true
)users
表和user_attributes
表。users
将具有id、user_type、username 等
,user_attributes
将具有id、user_id、attribute_name、value
。但是,如果两个用户之间的不同属性很少且非常稳定,那么您应该考虑使用 单表继承。
祝你好运!
This greatly depends on how many the different attributes between the teacher and student there'll be as well as how often new unique attributes will be added or removed. If the case is that they will differ a lot, you have two choses:
has_many :user, :polymorphic => true
)users
table and auser_attributes
table.users
would haveid, user_type, username, etc.
anduser_attributes
would haveid, user_id, attribute_name, value
.If, however, your different attributes between the two users are few and pretty rock solid, you should just consider using Single Table Inheritance.
Good luck!
在本例中,我只需使用一个名为
teacher
的布尔列。如果为真,则用户是教师。如果是假的,那就是学生。无需创建另一个模型。如果您想要两个以上角色(例如学生、教师、管理员、看门人(?)),您可以添加另一个名为 UserGroup 的模型。您还必须在用户表中创建一个名为
user_group_id
的列。在新模型中,每个角色都有一行。然后,您指定以下关系:这将允许您将每个用户分配到特定组。
In this case, I'd simply go with a single boolean column called
teacher
. If true, the user is a teacher. If false, it's a student. No need to create another model.If you want more than two roles (say, student, teacher, administrator, janitor(?)), you can add another model called UserGroup. You'll also have to create a column in the users table called
user_group_id
. In the new model, you have a single row for each of the roles. Then, you specify the following relationships:This will allow you to assign each user to a specific group.