devise: instance the current_user using single table inheritance
Asked Answered
T

2

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
Traipse answered 19/6, 2012 at 17:57 Comment(3)
I also has got the same problemForelli
Have you added the 'type' column in users table? This is what makes Rails STI work.Memphis
Forget my bounty, current_user is well-instantiated.Jackijackie
B
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.

Bewitch answered 12/3, 2013 at 11:12 Comment(1)
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 ;)Jackijackie
L
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!

Lough answered 17/3, 2013 at 10:52 Comment(1)
I advise you to use only one user type and depend on roles to determine what to do..Lough

© 2022 - 2024 — McMap. All rights reserved.