我嘗試添加在我的應用程序的用戶多層次的多層次,這是想法,我能想出:添加的用戶訪問
class ApplicationController < ActionController::Base
before_filter :setup , :authorize
protect_from_forgery
def setup
@minimum_permission = "admin"
end
def authorize
perm = { admin: 3 , moderator: 2 , reader: 1 }
perm.default = 0
if User.find_by_id(session[:user_id])
unless perm[session[:user_permission].to_s.to_sym] >= perm[@minimum_permission.to_sym]
redirect_to global_login_url, notice: "you need to have "[email protected]_permission+" privileges to access this page"
end
else
redirect_to global_login_url, notice: "Please log in"
end
end
end
在我看來,生病做這樣的事情:
class FieldsController < ApplicationController
skip_before_filter :authorize
# GET /fields
# GET /fields.json
def index
@minimum_permission = "moderator"
authorize
@fields = Field.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @fields }
end
end
....
end
,這是我的會話控制器:
class SessionsController < ApplicationController
skip_before_filter :authorize
def new
end
def create
user = User.find_by_cpf_no(params[:cpf_no])
if user and user.authenticate(params[:password])
session[:user_id] = user.id
session[:user_permission] = user.permission
session[:user_name] = user.name
redirect_to fields_url, alert: "successfully logged in"
else
redirect_to fields_path, alert: "Invalid user/password combination"
end
end
def destroy
session[:user_id] = nil
session[:user_permission] = nil
session[:user_name] = nil
redirect_to root_path, notice: "Logged out"
end
end
這個工作得很好誰是登錄的人!但是當我嘗試訪問索引時沒有登錄,我得到這個錯誤:
「在此操作中渲染和/或重定向被多次調用。請注意,您只能調用渲染或重定向,並在最重要的是每個動作一次,還要注意,既不是重定向也不是渲染終止了動作的執行,所以如果你想在重定向後退出動作,你需要做一些類似「redirect_to(...)並返回」。
我該如何解決這個問題?還有沒有更好的方法來處理多個級別的用戶? 謝謝
你是對的錯誤。事實上,即使在我的redirect_to()之後,我的索引控制器也沒有停止執行。使用「返回redirect_to()」根據這裏的答案 http://stackoverflow.com/questions/820781/how-do-i-stop-controller-execution-after-using-redirect-to-using-rails 由斯利普·道格拉斯解決我的問題, – viswa