【问题标题】:Audited Gem current_user_method not working审核的 Gem current_user 方法不起作用
【发布时间】:2018-06-15 23:44:28
【问题描述】:

我在我的应用程序中使用 Audited gem 来跟踪用户日志。除当前用户跟踪外,一切正常。

就我而言,我有 2 个模型:InstructorStudentInstructor 将是current_admin_user,我需要手动找到学生。

为了克服这个问题,我尝试覆盖 current_user_method 并在初始化程序中创建一个 audited.rb 文件,其内容如下:

Audited.current_user_method = :current_admin_user

这工作正常,但是当我使用任何其他方法时,例如 current_user_or_student ...

Audited.current_user_method = :current_user_or_student

application_controller.rb ...

def current_user_or_student
  current_admin_user || InstructorStudent.find_by_id(id)
end

它不会进入这个方法,即使current_admin_user 也不会存储在审计中。

为什么在application_controller.rb 中覆盖我的current_user_or_student 方法时没有调用它?

【问题讨论】:

  • 我查看了你的github个人资料,但我不知道你说的是哪个项目
  • @FabrizioBertoglio 这个项目不在我的 github 个人资料中。你需要项目来解决我的问题吗?
  • 可以分享详细的日志吗?
  • 我没有任何日志,但是当我在 audited.rb 中使用 current_admin_user 时,它正在存储用户,当我使用自定义方法 current_user_or_student 时,它没有存储。即使退出也不适用于该方法
  • 能否提供current_admin_user的出处?您是否在初始化程序中设置Audited.current_user_method?或者您是否尝试在运行时动态更改它?

标签: ruby-on-rails acts-as-audited


【解决方案1】:

您已将current_user_or_student 定义为:

def current_user_or_student
  current_admin_user || InstructorStudent.find_by_id(id)
end

假设current_admin_usernil,它将尝试找到InstructorStudent。您正在使用find_by_id,如果找不到具有该ID 的InstructorStudent,它将返回nil。这很可能就是正在发生的事情。从这个来源不清楚id 是什么——你确定它被设置为可以在instructor_students 中找到的id 吗?我鼓励你做以下调试:

def current_user_or_student
  current_admin_user || InstructorStudent.find(id)
end

如果方法的条件落入InstructorStudent.find 分支并且找不到id,这将引发错误。如果我的假设是正确的,这将证明无法找到 id,因此您的原始代码将返回 nil(而此更新的代码现在会出错)。错误消息还会告诉您id 的值是什么,您可以将其用于进一步调试。

或者,您可以在不更改代码的情况下进行调试,方法是运行您希望被审计但没有被审计的请求,然后检查服务器日志。您将看到查询在那里运行,并且可能也能够以这种方式进行调试。

【讨论】:

  • 我想我已经解决了这个问题,我只需要在 application_controller.rb 中添加 before_action :current_user_or_student 其他一切正常。现在它也可以正常工作了
  • 它不能以这种方式工作,我不知道我的应用程序控制器有什么问题,甚至 `before_filter :audited_user` 也无法正常工作。并且它不会在任何操作之前调用:(
【解决方案2】:

最后我解决了我的问题,我正在使用 STI(单表继承)。 我的其他讲师控制器不是从应用程序控制器继承的。所以我的current_user_or_student 没有被要求进行讲师登录。

为了克服这个问题,我创建了一个名为 audited_user.rb 的控制器关注点

并写下关注的方法

def current_user_or_student
  current_admin_user || InstructorStudent.find_by_id(id)
end

并将这个问题包含在我的讲师基础控制器和应用程序控制器中。 现在一切正常,我的审核用户也正确保存。

我希望这可以节省任何其他时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    相关资源
    最近更新 更多