简体   繁体   中英

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. The value could be admin, salesperson, instructor or student.

Now I have a ScheduledSession model that an Instructor is supposed to teach. I have an instructor_id column, which is supposed to have an id from the users table (an user with a role of instructor).

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. or setup something like belongs_to :user, :as instructor in the ScheduledSession model, but I get error Unknown key :as .

How would you set this up?

You want to set up your belongs_to slightly differently in the ScheduledSession model.

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.

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. Without it, you'll have no mechanism to retrieve the scheduled_sessions associated with a user.

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. You'll still store all of these in the same table, but ActiveRecord will make it easier for you to compartmentalize them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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