7

I have 3 kind of users in my app: Club, Person, and Admin. Each one is very different from each other, which means they almost don't share any attributes except for the authentication data, so that's why i'd rather use 3 different models. Also, i want to enable a single authentication model for all these kinds of users, using Authlogic, and handle Authorization using CanCan.

Initially i thought of something like this.

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

And for each one i would have

class Club < User end
class Admin < User end

But then the User table would be cluttered with all the columns of the other kinds of users and they will remain null.

Another option would be

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 kind of user, a role would be assigned. The problem is that accessing the properties of the method would be something like user.role.logo. One way i can think to solve this is by using delegate but still i don't know if that's the best option.

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

2
  • do you really need 3 different models? I mean for other reason than Authorization... Commented Jan 18, 2012 at 18:45
  • The reason is that the 3 kind of users are very different one from each other, so i wouldn't like a single model with a bunch of NULL fields in the database. Commented Jan 18, 2012 at 18:49

2 Answers 2

2

Like you suggest, I would create a User model to handle authentication. Then you can create a one-to-one polymorphic relationship between the User model and your roles' models. Your User model will have to include role_type (which is a string) and role_id (which is an integer) attributes.

User.rb

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

Admin.rb

class Admin < ActiveRecord::Base
  has_one :role
end

You can test what class a user's role is and access its attributes. For example:

User.first.role.is_a? Admin
=> true
User.first.role.last_name
=> "Smith"
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are trying to achieve role based authorization. Have a look at the wiki page in cancan.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.