【问题标题】:Can I automatically save the current user details using ActiveRecord callbacks?我可以使用 ActiveRecord 回调自动保存当前用户详细信息吗?
【发布时间】:2011-03-07 17:12:41
【问题描述】:

我想使用 ActiveRecord 的 before_save 回调来帮助我跟踪哪些用户编辑了哪些记录。例如

class Foo < ActiveRecord::Base
  before_save
   self.edited_by = curent_user.username
  end
  ....
end

我在这里遇到的问题是 Foo 不知道 current_user 是什么,因为它来自控制器助手。

我意识到,我可以在控制器中完成这一切。但如果可以的话,最好把它放到 before_save 回调中。

【问题讨论】:

标签: ruby-on-rails activerecord callback


【解决方案1】:

最简单的方法是让你的模型更丰富:

class Article
  def edit!(editor)
    self.edited_by = editor.name
    self.save!
  end
end

无需使用回调。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2017-03-08
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    相关资源
    最近更新 更多