2013-09-30 90 views
0

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

这是我到目前为止已经完成: 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 

的routes.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' 
. 
. 
. 

ability.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 

当我运行耙路线,我获得了Devise和Rails_admin路线的路线,以及“上传”路线。 我真的试图解决这个愚蠢的错误,但老实说,我跑出了想法。我会很感激你能为我提供的任何帮助。先谢谢你。

回答

3

问题是您的before_filter需要用户在您的ApplicationController中登录。基本上,您要求您的用户在访问登录页面之前先登录。

您可以通过使用色器件内置的方法:authenticate_user解决这个问题:

before_filter :authenticate_user! 

或者,你也可以指定before_filter不从DeviseController动作运行。

before_filter :require_login, :unless => :devise_controller? 
+0

谢谢你,工作。 – Splendonia