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?
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.
class User < ActiveRecord::Base
belongs_to :role, :polymorphic => true
end
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With