4

I want to do this:

application_controller.rb:

class ApplicationController < ActionController::Base
  alias_method :devise_current_user, :current_user

  private

  def current_user
    if params[:user].blank?
      puts "!found user"
      devise_current_user
    else
      puts "found user"
      user = User.find_by(email: params[:user][:email])
      return detect_role(user)
    end
  end

  def detect_role(user)
    roles = user.roles_name
    user = if roles.include?("mentor")
             user.becomes(Mentor)
           elsif !roles.include?("admin") && !roles.include?("mentor")
             user.becomes(Student)
           else
             user
           end
  end
end

but still does not go out to override current_user

log: https://gist.github.com/anonymous/e0a5fb593b020b16a0cd2ae9d539b92a

Pavel
  • 2,103
  • 4
  • 23
  • 41
  • 1
    Possible duplicate of [Where to override current\_user helper method of devise gem](https://stackoverflow.com/questions/10349606/where-to-override-current-user-helper-method-of-devise-gem) – lcguida Sep 19 '17 at 09:53
  • I want to override User to different class, but always got User class – Pavel Sep 20 '17 at 21:52
  • If not getting a user class this is nor a devise problem, but probably a problem in your User retrieval logic. Can you show how you coded these subclasses and the user class? How are their relations? – lcguida Sep 21 '17 at 07:54
  • https://gist.github.com/anonymous/d1e09453c6cc3dd0c17e4faec1aca271 – Pavel Sep 21 '17 at 09:03
  • So you do have a `type` column which determines the `User` class? – lcguida Sep 21 '17 at 10:41
  • Just be clear, the problem is `#detect_role` does not return a user of the right class, which should be one of the subclasses based on the roles, right? How do you know it's not working? The log you showed didn't hit the correct branch. – EJAg Sep 24 '17 at 00:57

2 Answers2

2

This helped me:

class ApplicationController < ActionController::Base
  alias_method :devise_current_user, :current_user

  private

  def current_user
    user = if params[:user].blank?
             devise_current_user
           else
             User.find_by(email: params[:user][:email])
           end
    detect_role(user) if !user.blank?
  end

  def detect_role(user)
    roles = user.roles_name
    user = if roles.include?("mentor")
             user.becomes(Mentor)
           elsif !roles.include?("admin") && !roles.include?("mentor")
             user.becomes(Student)
           else
             user
           end
  end
end
Pavel
  • 2,103
  • 4
  • 23
  • 41
0

Use

super

keyword and then right your override code like this;

def current_user
  super
  ----your code goes here ---
end
Sam
  • 1,623
  • 1
  • 19
  • 31
  • Added `super` but it did not help log: https://gist.github.com/anonymous/688eeb1568f359bd2ad98e735d4972e7 – Pavel Sep 19 '17 at 13:03