【问题标题】:Authlogic's current_user object in models模型中 Authlogic 的 current_user 对象
【发布时间】:2010-03-19 10:57:38
【问题描述】:

我需要知道模型中当前用户的ID:

def after_save
  desc, points=nil, nil

  if answer_index == daily_question.correct_answer_index 
    desc = I18n.t('daily_question.point_log.description.correct') 
    points=daily_question.points
  else
    desc = I18n.t('daily_question.point_log.description.incorrect')
  end

  current_user.give_points(:description => desc,
                           :points => points
                          )
end

但我猜这不是怎么做的?

问候,

雅各布

【问题讨论】:

    标签: ruby-on-rails authlogic


    【解决方案1】:

    假设用户已登录,您可以使用

    UserSession.find.user

    您可能需要添加检查以确保 UserSession.find 在调用 .user 之前返回某些内容

    【讨论】:

    • current_user 不就是 self 吗?如果您在控制器中的某处调用 current_user.save,那么 :after_save :something 将了解有关用户的所有信息...除非另一个用户可以作为 current_user 响应,否则我猜您并不真的需要“current_user”方法。 .
    • 我只是想自己解决这个问题。谢谢!
    • 这允许奇妙的验证方法,如 只有当用户 == 当前用户时才能更改密码
    【解决方案2】:

    这是不可能的。
    current_user 依赖于会话,该会话在模型中不可用(这很正常。模型与上下文无关)。

    您应该将用户作为参数传递给模型。

    【讨论】:

    • 为了保持 MVC 兼容是正确的......当然从技术上讲它是不正确的。这并不意味着这是一种好的做法。
    • 我的意思是说“不可能”是不正确的。我同意你关于不良做法的看法。
    【解决方案3】:

    使用 Authlogic 时访问模型中 current_user 的最佳方法是使用 Sentiant 用户 - https://github.com/bokmann/sentient_user 有一个完整的文档说明如何使用它。

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多