Devise with many models

190 views
Skip to first unread message

ebf...@hotmail.com

unread,
Dec 17, 2010, 2:28:55 PM12/17/10
to Devise
Oops! :-)
Have been looking like crazy for tutorials on STI (Single Table
Inheritance) and polymorphic associations to devise and use with many
models.
I'm in trouble here, I have three models ('admin.rb', 'pesquisador.rb'
and 'bolsista.rb'), the typical case of teacher, student and
administrator..
But the devise works only with a model, usually 'user.rb' as shown in
many tutorials..
What I wonder is how can I relate the models so I can create a generic
model 'usuario.rb'and use the devise, having an interface with
administrative privileges ..

Thanks in advance! :-D

Bharat

unread,
Dec 18, 2010, 9:08:00 AM12/18/10
to Devise
So Devise is mostly an Authentication application. I would use an
"Authorization" system such as cancan by Ryan Bates:

https://github.com/ryanb/cancan

You can then use just the User model and define as many roles as you
like. Here is an example for using Devise with cancan:

https://github.com/zmbmartin/devise-roles-user-management

Regarding STI and Polymorphic associations, they are topics in
themselves, I would use Rails Guides to learn about it.

Hope this helps.

Bharat

AppleII717

unread,
Dec 18, 2010, 9:10:16 AM12/18/10
to Devise
I did the polymorphic approach, but the project died and never quit
got it right. Since then I've been using model that inherit User,
mainly because the data (name, address etc) were about the same

http://groups.google.com/group/plataformatec-devise/browse_thread/thread/bbc3bb0e245ad4d3/f4667ffce8faadec?lnk=gst&q=polymorphic#f4667ffce8faadec

If there a lot of differences, the polymorphic is really fairly easy.
If you don't try to mix nested attributes you can use the same
approach used on inherited Users. Just put a link in the Teacher
profile (whatever the can update) to the devise user edit.

Some chuck of code from a couple different system:

class User < ActiveRecord::Base
belongs_to :loginable, :polymorphic => true
....

class Employee < ActiveRecord::Base
belongs_to :office
has_many :projects
has_one :user, :as => :loginable

application controller clip (replace user_type with loginable_type for
polymorphic)

def after_sign_in_path_for(resource_or_scope)
#scope = Devise::Mapping.find_scope!(resource_or_scope)
case current_user.user_type
when "admin"
user_session[:namespace] = current_user.user_type
return admin_welcome_index_path
when "company"
user_session[:namespace] = current_user.user_type
return company_welcome_index_path
when "project"
user_session[:namespace] = current_user.user_type
return project_welcome_index_path
when "citizen"
user_session[:namespace] = current_user.user_type
return citizen_welcome_index_path

else
user_session[:namespace] = 'citizen'
super
end
end

Hope it give you a start.

Steve
Reply all
Reply to author
Forward
0 new messages