0

我使用devise并尝试做接下来的事情:

当用户登录/注册时,我想通过他的 role_id 重定向他(我让一些用户的 id 为 1,其他用户为 2)。

如果他的 role_id 为 1,则将他重定向到tasksadmins_path,否则重定向到workers_path

所以我尝试了类似的东西:

routes.rb

devise_for :users, :controllers => { :sessions => 'user_sessions'} do
   get '/users/sign_out' => 'devise/sessions#destroy'
   root to: "workers#index"
end

resources :tasksadmins

resources :workers

root to: "workers#index"

这是我的application_controller.rb

class ApplicationController < ActionController::Base
    include ApplicationHelper

    protect_from_forgery
    before_filter :authenticate_user!

    rescue_from CanCan::AccessDenied do |exception|
        if current_user.role_ids == [2]
           redirect_to root_url
        else
           redirect_to tasksadmins_path
        end
    end
end
4

2 回答 2

1

针对这种情况,Devise 有特殊的方法。您可以覆盖 after_sign_in_path_for。在应用程序控制器中

def after_sign_in_path_for(resource_or_scope)
 if resource_or_scope.is_a?(User)
  town_path
 else
  users_path
 end
end
于 2013-01-31T10:50:28.160 回答
0

after_sign_in_path_for不起作用,所以我添加到“创建”下一行:

一开始,我写道:

resource = warden.authenticate!(:scope => resource_name)

然后我在“创建”函数的末尾写道:

sign_in(resource_name, resource)

if current_user.role_ids == [2]
   respond_with resource, :location => workers_path
else
   respond_with resource, :location => tasksadmins_path
end

所以我的创作看起来是这样的:

class UserSessionsController < Devise::SessionsController
    include ApplicationHelper

    def create

        resource = warden.authenticate!(:scope => resource_name)

        require "uri"
        require "net/http"

        ## get the user id from the database
        user_id = session['warden.user.user.key'][1][0];

        ## get the row by id
        user = User.find(user_id)

        # ============================
        # Ensure that a user exists
        # ============================

        code, body = http_request(Net::HTTP::Put.new("/api/v1/users/external/#{user_id}"), email: user.email);
        if code != 200
           Rails.logger.error("Unable to register user #{current_user.email} at Licensario");
        end

        sign_in(resource_name, resource)

        if current_user.role_ids == [2]
           respond_with resource, :location => workers_path
       else
           respond_with resource, :location => tasksadmins_path
       end

    end
end
于 2013-02-03T12:44:56.853 回答