0

我正在尝试使用 ActiveRecord 回调添加当前用户信息以进行记录,但我不知道如何做到这一点。我尝试了 Thread.current[:user],但在结果中我看到线程值是从另一个用户会话访问的。我在生产中使用 Passanger,但同时我正在使用正确获得用户价值的acts_as_audited。最好/最安全的方法是什么?

4

1 回答 1

0

当前用户无法从 ActiveRecord 模型中访问。这是由于 Rails 中的关注点分离——当前用户和会话是属于控制器领域的概念。

您需要获取相关数据并将其传递到模型中,以便您的回调起作用。一种方法是使用访问器方法:

# model
attr_accessor :current_user

def my_callback
  # do something with current_user
  self.some_attribute = current_user
end

# controller
@model = MyModel.find(params[:id])
@model.current_user = current_user # assuming you have a controller method that does this
@model.save!

您应该将current_user访问器重命名为有意义:例如。如果您正在跟踪博客文章的作者,请调用它authorresponsible_user类似的名称,因为current_user一旦保存模型就没有任何意义。

于 2013-02-07T20:15:06.390 回答