0

我希望在用户登录后,根据它的角色,它会重定向到某个页面,我已经阅读了 thisthis和 this, 但我似乎做错了,我已经尝试了每一个和每个都给了我问题。

我想要的是,在用户登录后,它将他/她重定向到 x_path,这在技术上是可行的,但在登录后,它会尝试加载 redirect_user 模板。

应用控制器

 class ApplicationController < ActionController::Base
      before_filter :authenticate_user!
      protect_from_forgery

      rescue_from CanCan::AccessDenied do |e|
        redirect_to new_user_session_path, alert: e.message
      end

  def redirect_user
    if current_user.role == 'Administrator'
      redirect_to rails_admin_path
    elsif current_user.role == 'C1' or 'D1' or 'M1' or 'M2'
      redirect_to upload_files_path
    end
  end 
end

路由.rb

Siteconfigurationlistgenerator::Application.routes.draw do
  devise_for :users
  match '/' => 'application#redirect_user'

能力

class Ability
  include CanCan::Ability

  def initialize(user)
    #Define abilities for the passed in user here.
    user ||= User.new #guest user (not logged in)
    #a signed-in user can do everything
    if user.role == 'Administrator'
      #an admin can do everything
      can :manage, :all
      can :access, :rails_admin   # grant access to rails_admin
      can :dashboard              # grant access to the dashboard
    elsif user.role == '1' or 'M1' or 'D1' or 'M2'
      can :manage, [MaterialList, Inventory, UploadFiles, DownloadTemplate]
      cannot :access, :rails_admin
      cannot :dashboard
      can :access, [:upload_files, :download_template]
    end

  end
end

目前,正如我所拥有的那样,它说找不到模板,它在视图/应用程序文件夹中查找redirect_user模板,它不应该,它应该只是重定向

4

1 回答 1

0

routes.rb应该有:

devise_for :users, :controllers => { :sessions => "sessions" }

然后,您需要创建一个sessions_controller.rb

class SessionsController < Devise::SessionsController

  protected

  def after_sign_in_path_for(resource)
    if resource.role == 'Administrator'
      rails_admin_path
    elsif resource.role == 'C1' or 'D1' or 'M1' or 'M2'
      upload_files_path
    else
      super
    end
  end

end

您会注意到此方法返回路径,它不调用redirect_to我还添加了一个调用,super以便在没有条件匹配时调用默认行为。

于 2013-10-03T20:19:51.087 回答