【发布时间】:2011-08-01 05:11:20
【问题描述】:
我的应用程序中的 authlogic 运行得很好,但我正在扮演自己的角色(我是 Rails 新手,想学习......)
所以我有一个用户模型、一个角色模型和一个用户会话模型。用户acts_as_authenticated。
在我的 application_controller 中
protect_from_forgery
helper_method :current_user, :is_admin, :is_group_coach, :is_group_leader
private
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.record
end
def is_admin
current_user.role_id == 3
end
def is_group_coach
current_user.role_id == 2
end
def is_group_leader
current_user.role_id == 1
end
那我在视图中做一个简单的if is_admin...
但它为 nil:NilClass 返回未定义的方法 `role_id'
我认为它这样做是因为 current_user 实际上运行的是 UserSession 模型而不是用户......我怎样才能修改它以按预期运行?
【问题讨论】:
-
您的用户尚未登录。添加
before-filter以保护需要登录用户的操作。另外,考虑使用CanCangem,而不是在代码中到处检查角色。
标签: ruby-on-rails authlogic roles