8

I am using rails 3.0.9 and devise for authentication. Now I'm trying to use single table inheritance because I need to use polymorphism, so I have two classes: UserType1 and UserType2, which inherit from User class. I need that Devise instance correctly the current_user depending the type of user.

For example,

class User < ActiveRecord::Base
 #devise and other user logic 
end

class UserType1 < User
  def get_some_attribute
     return "Hello, my type is UserType1"
  end
end

class UserType2 < User
  def get_some_attribute
   return "Hello, my type is UserType2"
  end
end

In controller 

class MyController < ApplicationController
  def action
    @message = current_user.get_some_attribute #depending the type using polymorphism
    render :my_view
  end
end
brianfalah
  • 191
  • 2
  • 11

2 Answers2

5

it's exactly what you need : http://blog.jeffsaracco.com/ruby-on-rails-polymorphic-user-model-with-devise-authentication

you need to override the sign in path method in your application controller, hope it help.

jeffsaracco
  • 1,259
  • 12
  • 21
rbinsztock
  • 3,025
  • 2
  • 21
  • 34
  • Sorry, as I said in comments + answer, forget my bounty, `current_user` is in fact well instantiated by STI mechanism. I put the bounty too fast without testing so far ;) – Thomas Guillory Mar 12 '13 at 11:26
1

You will need to add get_some_attribute method inside User model

Module User < ActiveRecord::Base

   #devise and other user logic 

   def get_some_attribute
      #You can put shared logic between the two users type here
   end

end

then, to override it in the user sub types, like this:

Module UserType1 < User

   def get_some_attribute
      super
      return "Hello, my type is UserType1"
   end

end

Module UserType2 < User

   def get_some_attribute
      super
      return "Hello, my type is UserType2"
   end

end

Then, current_user.get_some_attribute will work as you expecting, if you like to read more about overriding methods in Ruby, you can read about it here

I added super as I assumed that you have some shared logic in get_some_attribute, as it will call get_some_attribute in User model, you can remove it if you don't need it.

Good luck!

simo
  • 23,342
  • 38
  • 121
  • 218
  • I advise you to use only one user type and depend on roles to determine what to do.. – simo Mar 19 '13 at 15:23