我让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模型,而不是用户……我如何才能将其修改为按预期运行?
发布于 2011-08-01 05:11:20
在这段代码中,您的current_user_session方法可能是不完整的,因为您不能在没有参数的情况下调用find,所以我猜想,如果用户没有登录,那么里面有一个防止nil值或类似值的保护。如果用户有可能无法登录,那么您的方法应该考虑到这一点,并且只在current_user上调用可用的方法。
你的方法应该是这样的:
def is_admin
current_user && current_user.role_id == 3
end
def is_group_coach
current_user && current_user.role_id == 2
end
def is_group_leader
current_user && current_user.role_id == 1
end这将防止测试在当前没有用户登录到网站时中断。
https://stackoverflow.com/questions/6891616
复制相似问题