【问题标题】:How can I pull the User.role_id through a UserSession Model如何通过 UserSession 模型提取 User.role_id
【发布时间】: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 以保护需要登录用户的操作。另外,考虑使用CanCan gem,而不是在代码中到处检查角色。

标签: ruby-on-rails authlogic roles


【解决方案1】:

您的 current_user_session 方法在此代码 sn-p 上可能不完整,因为您无法在没有参数的情况下调用 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

如果网站上当前没有用户登录,这将防止测试中断。

【讨论】:

  • UserSession 不是 ActiveRecord 模型,它只是一个类。在 Authlogic 中,他们试图使其看起来像其他模型以保持一致性。
猜你喜欢
  • 2011-03-26
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
  • 2019-01-14
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
相关资源
最近更新 更多