2013-09-30 88 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