How to implement authentication / authorization with multiple models using Rails?

I have 3 kinds of users in my application: Club, Person and Admin . Each of them is very different from each other, which means that they hardly use any attributes except authentication data, so I would prefer to use 3 different models . In addition, I want to enable a single authentication model for all these types of users using Authlogic and handle authorization using CanCan .

Initially, I thought of something like that.

class User < ActiveRecord::Base # This class has the email and password in order to be authenticated with Authlogic end 

And for each of them I would have

 class Club < User end class Admin < User end 

But then the User table will be cluttered with all columns of other types of users, and they will remain empty.

Another variant:

 class User < ActiveRecord::Base # This class has the email and password in order to be authenticated with Authlogic belongs_to :role, :polymorphic => true end 

And for each type of user a role will be assigned. The problem is that accessing the method properties will be something like user.role.logo . One way I can think of is to solve this using a delegate, but still I don't know if this is the best option.

The question is, how would you suggest me to implement this? What would be the best way?

+7
source share
2 answers

As you suggest, I would create a User model for authentication. Then you can create a one-to-one polymorphic relationship between the user model and the models of your roles. The user model must include the attributes role_type (which is a string) and role_id (which is an integer).

User.rb

 class User < ActiveRecord::Base belongs_to :role, :polymorphic => true end 

Admin.rb

 class Admin < ActiveRecord::Base has_one :role end 

You can check which class belongs to the user role and access its attributes. For example:

 User.first.role.is_a? Admin => true User.first.role.last_name => "Smith" 
+2
source

I think you are trying to achieve role-based authorization. Check out the wiki cancan page.

https://github.com/ryanb/cancan/wiki/Role-Based-Authorization

+1
source

All Articles