redirect_to无法正常工作

时间:2013-01-31 09:54:52

标签: ruby-on-rails redirect devise

我使用devise并尝试做下一件事:

当用户登录/ up时,我想通过他的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

2 个答案:

答案 0 :(得分:1)

Devise对这种情况有特殊的方法。您可以覆盖after_sign_in_path_for。在ApplicationController中

def after_sign_in_path_for(resource_or_scope)
 if resource_or_scope.is_a?(User)
  town_path
 else
  users_path
 end
end

答案 1 :(得分:0)

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

一开始,我写道:

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

然后我在'create'函数的末尾写道:

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
相关问题