【发布时间】:2011-05-17 16:29:17
【问题描述】:
我正在尝试使用 Authlogic 实现角色,以限制我的 rails 应用程序中的控制器访问。一旦我使用 load_and_authorize 和 filter_resource_access 实现它,我就无法以任何角色访问控制器。
在我的用户模型中,我有一个角色字段,其中 has_many roles_users 指向角色模型。所以用户 1 是“管理员”,有一个角色分配 1,它链接到角色 1,即“管理员”。
ability.rb
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
can :read, InstallQuote
can :create, InstallQuote
if user.role? :admin
can :manage, :all
end
application_controller.rb
helper :all
protect_from_forgery # See ActionController::RequestForgeryProtection for details
helper_method :current_user_session, :current_user
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = exception.message
redirect_back_or_default(root_path)
end
before_filter { |c| Authorization.current_user = c.current_user }
filter_parameter_logging :password, :password_confirmation
protected
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
clients_controller.rb
class ClientsController < ApplicationController
# before_filter :authenticate, :only => [:edit, :update, :show, :index]
load_and_authorize_resource # For declarative authorization
filter_resource_access
# belongs_to :company
# before_filter :require_user, :only => [:edit, :update, :index, :destroy]
# before_filter :admin_user, :only => :destroy
helper_method :sort_column, :sort_direction
before_filter :correct_user, :only => [:edit, :update, :show, :index]
user.rb
acts_as_authentic
has_many :roles_users
has_many :roles, :through => :roles_users
before_create :setup_role
attr_accessible :email, :login, :first_name, :last_name, :role_id, :password, :password_confirmation, :active
(我已经注释掉了我还不想放弃的旧代码)。
有人知道我错过了什么吗?
【问题讨论】:
标签: ruby-on-rails-3 authlogic roles cancan