我希望用户登录后,根据其重定向到某个页面的角色,我已阅读this,this,and this但我可以'似乎做得对,我已经尝试了每一个,每个都给了我一些问题。
我想要的只是在用户登录后,它将他/她重定向到x_path,我在技术上有效,但在登录后,它会尝试加载redirect_user模板。
的ApplicationController
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
的routes.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模板,在views / application文件夹中它不应该,它应该只是重定向
答案 0 :(得分: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
的调用,以便在没有任何条件匹配时调用默认行为。