0

我是 ruby​​ 和 Rails 的新手。我在我的应用程序中使用 Devise 和 CanCan 以及 Rails_Admin。我正在尝试做->如果用户已经登录,并且它是管理员,则重定向到 rails_admin_path 如果它不是管理员而只是用户然后重定向到'upload_path',如果它没有登录则重定向到登录路径,但是可能由于我缺乏知识,我正在创建一个无限重定向循环。即使我尝试在没有“require_login”过滤器的情况下访问 sign_in。

这是我到目前为止所做的:application_controller.rb

class ApplicationController < ActionController::Base
  before_filter :require_login
  protect_from_forgery

 #IDEA 1
 #def require_login
 #   if current_user.role? == 'Administrator'
 #      redirect_to rails_admin_path
 #   elsif current_user.role? == (('C1' or 'D1') or ('M1' or 'M2'))
 #      redirect_to upload_path
 #   end
 # end  

#I saw this somewhere and It doesn't work either
 def require_login
   redirect_to new_user_session_path, alert: "You must be logged in to perform this action" if current_user.nil?
 end
    rescue_from CanCan::AccessDenied do |e|
   redirect_to new_user_session_path, alert: e.message
   end

end

路线.rb

Siteconfigurationlistgenerator::Application.routes.draw do

  mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'

 devise_for :users
  # The priority is based upon order of creation:
  # first created -> highest priority.

  match 'upload' => 'upload_file#new'
.
.
.

能力.rb

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 == (('C1' or 'M1') or ('D1' or 'M1'))
       # can :manage, [ProductList, Inventory]
       # can :read, SiteConfigurationList
   #  end
   end

  end

当我运行 rake 路由时,我得到了 Devise 和 Rails_admin 路由的路由,以及“上传”路由。我真的试图修复这个愚蠢的错误,但老实说我没有想法。我很感激你能为我提供的任何帮助。先感谢您。

4

1 回答 1

3

问题是你有一个before_filter需要用户登录的应用程序控制器。基本上,您要求您的用户在访问登录页面之前登录。

您可以使用设计的内置方法解决此问题:authenticate_user

before_filter :authenticate_user!

或者,您可以指定您before_filter不在 DeviseController 中的操作上运行。

before_filter :require_login, :unless => :devise_controller?
于 2013-09-30T15:05:45.963 回答