繁体   English   中英

如何使用devise和cancan在sign_in之后不加载模板的情况下使Rails重定向

[英]How to make rails redirect without loading the template after sign_in with devise and cancan

我想在用户登录后根据它重定向到某个页面的角色,已经读过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

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

目前,据我所知,它表示未找到类似模板的内容,它在views / application文件夹中查找redirect_user模板,不应,它应该只是重定向

您的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的调用,以便在没有条件匹配时调用默认行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM