after_save 回调将 updated_by 列设置为 current_user [英] after_save callback to set the updated_by column to the current_user
本文介绍了after_save 回调将 updated_by 列设置为 current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 after_save 回调将 updated_by 列设置为 current_user.但是 current_user 在模型中不可用.我该怎么做?
I would like to use an after_save callback to set the updated_by column to the current_user. But the current_user isn't available in the model. How should I do this?
推荐答案
需要在控制器中处理.首先对模型执行保存,如果成功则更新记录字段.
You need to handle it in the controller. First execute the save on the model, then if successful update the record field.
示例
class MyController < ActionController::Base
def index
if record.save
record.update_attribute :updated_by, current_user.id
end
end
end
另一种选择(我更喜欢这个)是在您的模型中创建一个包装逻辑的自定义方法.例如
Another alternative (I prefer this one) is to create a custom method in your model that wraps the logic. For example
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
这篇关于after_save 回调将 updated_by 列设置为 current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文