Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

devise: instance the current_user using single table inheritance

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
like image 670
brianfalah Avatar asked Jun 19 '12 17:06

brianfalah


2 Answers

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.

like image 101
rbinsztock Avatar answered Sep 21 '22 20:09

rbinsztock


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!

like image 44
simo Avatar answered Sep 19 '22 20:09

simo