简体   繁体   English

Rails 3.如何设置用户模型以充当不同角色?

[英]Rails 3. How to setup User model to act as different roles?

I setup roles for the User model, for now, I just have a role string column for the users table. 我为User模型设置了角色,现在,我只为users表提供了一个角色字符串列。 The value could be admin, salesperson, instructor or student. 该值可以是管理员,销售员,讲师或学生。

Now I have a ScheduledSession model that an Instructor is supposed to teach. 现在,我有一个讲师应该教的ScheduledSession模型。 I have an instructor_id column, which is supposed to have an id from the users table (an user with a role of instructor). 我有一个utoror_id列,该列应该具有用户表(具有指导者角色的用户)中的ID。

So how can I setup the association in the models? 那么如何在模型中设置关联? in the User model is doesn't seem right to add has_many :scheduled_sessions because if the role is a salesperson or an admin, it just doesn't feel right. 在User模型中添加has_many :scheduled_sessions似乎不正确,因为如果角色是销售人员或管理员,那感觉就不合适。 or setup something like belongs_to :user, :as instructor in the ScheduledSession model, but I get error Unknown key :as . 或在ScheduledSession模型中设置类似belongs_to :user, :as instructor ,但出现错误Unknown key :as

How would you set this up? 您将如何设置?

You want to set up your belongs_to slightly differently in the ScheduledSession model. 您要在ScheduledSession模型中将自己的归属设置设置为稍有不同。

belongs_to :instructor, :class_name => 'User, :foreign_key => 'user_id'

This allows you to refer to the instructor of a ScheduledSession object and have it point to an entity in the User table. 这使您可以引用ScheduledSession对象的instructor ,并使其指向User表中的实体。

There's no way around having a has_many relationship on your User model if you want to pursue a role based User with each user having a single role. 如果您想追求一个基于角色的用户,而每个用户只有一个角色,则无法在用户模型上拥有has_many关系。 Without it, you'll have no mechanism to retrieve the scheduled_sessions associated with a user. 没有它,您将无法检索与用户关联的Scheduled_sessions。

An alternative might be to use Single Table inheritance here, which would allow you to create Admin users who don't have SchededSessions, but Instructors who do. 一种替代方法是在此处使用“单表”继承,这将允许您创建不具有SchededSessions的Admin用户,但具有创建者的Admin用户。 You'll still store all of these in the same table, but ActiveRecord will make it easier for you to compartmentalize them. 您仍将所有这些存储在同一表中,但是ActiveRecord将使您更容易将它们分隔开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM