我是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路線的路線,以及「上傳」路線。 我真的試圖解決這個愚蠢的錯誤,但老實說,我跑出了想法。我會很感激你能爲我提供的任何幫助。先謝謝你。
謝謝你,工作。 – Splendonia