问题
Thanks for reading.
I am using Devise and Rails 4. I want to add multiple User Models(admin, usertype1, usertype2) such that they inherit from the main User Model. I have searched many posts and come to the conclusion that I may use CanCan, which I do not want, or I may use Single Table Inheritance.
The way I see it is to add a type string-column to my main User model I created with Devise. I will also need to extend each sub-class from the parent as in:
class Admin < User
end
class Usertype1 < User
end
class Usertype2 < User
end
My question is: what do I do next? How exactly do I know how to access the type column? Do I also need to override the Devise Controller for the current_user helper method such that I can have current_admin for example?
Thanks again.
回答1:
You can also use the easy_roles gem. It is available on github. This gem provides a bitmask solution for your different user roles. You just must have one model, e.g User, this model gets an attribute "role". Just checkout the docs on github. Devise + easy_roles + CanCan is a very good setup, it is very convenient in my opinion. I use this quite often.
Link to github: https://github.com/platform45/easy_roles
回答2:
I'm not sure this really answers the original question. I am trying to set up multiple session controllers for Devise, and it seems like it really does require multiple models for this use case. Will post back when I've got a working version.
回答3:
STI will give you current_admin
, current_user1
and current_user2
Devise methods.
In application_controller.rb
, create a custom current_user
method like this:
def current_user
if current_admin
current_admin
elsif current_user1
current_user1
else
current_user2
end
end
helper_method :current_user
You will need some work on routes.rb and a custom sessions_controller.rb. See the accepted answer here Rails: Using Devise with single table inheritance
来源:https://stackoverflow.com/questions/18064649/rails-4-devise-multiple-user-models-sti