Rails Fan
Rails Fan

Reputation: 121

How to implement Rails associations when using roles instead of multiple models for user types

I need some advice on the best approach to take for the following.

I used to have Tutor, Student, Reservation models in my application.

I want a reservation to contain a Tutor and a Student.

Currently I am using devise for the user authentication, and I like the idea of using a generic User, and having roles defined for the users as many people have done with devise & cancan. It makes it easy to create an admin role for example. Thus I could have a role Tutor or Student contained within User.

Now my problem is that I can no longer use associations in the way I would like, e.g.

Reservation
  belongs_to :Tutor
  belongs_to :Student

because I no longer have an individual model for each type of user.

What should I do?

I found that if I have individual models for Tutor and Student then in devise I would need seperate links for logging in and editing each type of user.

Adding some links to similar questions

Multipe relationships in Rails where the class name does not match the association name

Upvotes: 1

Views: 1470

Answers (1)

PinnyM
PinnyM

Reputation: 35533

Just override the class name to use 'User':

class Reservation < ActiveRecord::Base
  belongs_to :tutor, :class_name => "User"
  belongs_to :student, :class_name => "User"
end

Upvotes: 1

Related Questions