after_save回调将updated_by列设置为current_user
我想使用after_save回调将updated_by列设置为current_user。 但是current_user在模型中不可用。 我该怎么做?
您需要在控制器中处理它。 首先在模型上执行保存,然后如果成功更新记录字段。
例
class MyController < ActionController::Base def index if record.save record.update_attribute :updated_by, current_user.id end end end
另一个替代方案(我更喜欢这个)是在模型中创建一个包装逻辑的自定义方法。 例如
class Record < ActiveRecord::Base def save_by(user) self.updated_by = user.id self.save end end class MyController < ActionController::Base def index ... record.save_by(current_user) end end
我已经根据Simone Carletti的建议实现了这个monkeypatch,据我所知, touch
只有时间戳,而不是用户ID。 这有什么不对吗? 这旨在与设计current_user
。
class ActiveRecord::Base def save_with_user(user) self.updated_by_user = user unless user.blank? save end def update_attributes_with_user(attributes, user) self.updated_by_user = user unless user.blank? update_attributes(attributes) end end
然后create
和update
方法调用这些:
@foo.save_with_user(current_user) @foo.update_attributes_with_user(params[:foo], current_user)