我想使用after_save
回调将updated_by
列设置为current_user
。但是模型中无法使用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。这样做有什么问题吗?这是为了与devise的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)
touch
只会更改时间戳,而不是用户ID。您是否发现任何问题?这是为了与设备当前用户一起使用。非常感谢您的任何意见! - Matt