我的应用程序中基于角色的授权基于cancan(使用rvm 1.9.2@rails_3_0_9和AuthLogic):
在我正在测试的视图中,我得到了这个:
错误的参数数量(1表示0)提取的来源(第12行):
12: %td = link_to 'Edit', edit_session_path(session) if can? :manage, @session
我应该解释Authlogic的常用身份验证类,User和User_session模型在此应用程序中替换为Contact和Contact_sessions。上面的会话模型实例是不认证的一部分。 (想想,法庭正在开会......)。这意味着你必须告诉cancan这个变化。
我在ApplicationController中重置了默认值:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
helper_method :current_ability #:current_contact
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
# = = = = = = = = = = = = logon controls = = = = = = = = = = = = = = = = = = =
private
# Override default assumption by CanCan
# https://github.com/ryanb/cancan/wiki/changing-defaults
# in ApplicationController
def current_ability
@current_ability ||= Ability.new(current_contact)
end
def require_contact
unless current_contact
redirect_to root_url, :notice => "You must be logged in to access this page."
return false
end
end
def current_contact_session
return @current_contact_session if defined?(@current_contact_session)
@current_contact_session = ContactSession.find
end
# return user model
def current_contact
return @current_contact if defined?(@current_contact)
@current_contact = current_contact_session && current_contact_session.record
end
end
角色和权利在我的Ability类中定义,此处:
class Ability
include CanCan::Ability
# Role Inheritance
# https://github.com/ryanb/cancan/wiki/Role-Based-Authorization
# in Ability#initialize
def initialize
if @contact.role? :visitor
can :read, [Home, Session]
end
if @contact.role? :camper
can :read, [Home, Contact_session, Session]
can :manage, Registration
end
if @contact.role? :admin
can :manage, [Home, Contact_session, Contact, Session]
end
if @contact.role? :superadmin
can :manage, :all
end
end
end
对于它的价值而言,此时我还没有向任何其他控制器添加任何代码(我想我可以决定一旦我能做什么?我想要的方法)。
知道这里有什么问题吗?我假设错误的参数数量是由can调用的东西?第12行的方法?我已经尝试了许多替代方案并产生了许多其他错误,但是一旦我清理它们,我就会回到这个错误。每个建议都将不胜感激!
答案 0 :(得分:1)
我明白了:Ability#initialize方法接受一个参数,它是当前用户对象,如果没有用户登录,你就可以默认这个(我的用户类在这个app中被一个名为Contact的用户替换) ):
def initialize(current_contact) current_contact || = Contact.create(:role =&gt;'visitor')#guests 用户(未登录)
另外,我发现我不需要这个角色? ApplicationController中的方法,因为明确指定权限并随时间添加它们非常简单和精确,就像这样(在Ability#initialize中):
if current_contact.role == 'superadmin' can :manage, :all end if current_contact.role == 'admin' can :manage,
[住宿,船舱,联系人,标识符,行程,付款,生化,会议,体育] 端
if current_contact.role == 'camper' can :read, Session can [:read,:update], Registration #:active => true, :user_id =>
user.id如果是他们自己的......为此添加代码 端
# A visitor can look around and register (but not manage
注册) if current_contact.role =='visitor' 可以:阅读,会话 可以:更新,注册 端