Thursday, September 28, 2017

Devise: override current_user (set different Class for user)

Leave a Comment

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

2 Answers

Answers 1

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 

Answers 2

Use

super

keyword and then right your override code like this;

def current_user   super   ----your code goes here --- end 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment