如何实现类似于“自动插入时间戳"的功能? [英] How can I achieve a functionality similar to "auto-insertion of timestamps"
问题描述
在我的大多数表格中,我有几个字段 created_by
和 updated_by
.这将包含创建或更新对象的用户的用户 ID.是否有可能具有类似 rails 如何处理 created_at
的功能?我基本上希望它的功能与时间戳插入相同.我应该能够在迁移脚本的列中定义并配置 rails 以在每次更改特定对象时从辅助方法中获取用户对象.有没有直接的方法来做到这一点,或者是否有一个插件可以做到这一点?
I have a couple of fields created_by
and updated_by
in most of my tables. This would contain the user id of the user who created or updated the Object. is it possible to have a similar function like how rails handles created_at
? I basically want it to function the same way as the timestamps insertion. I should be able to define in the columns in the migration script and configure rails to fetch the user object from a helper method everytime when it changes the particular object. Is there a direct way to do it or is there a plugin which does this?
推荐答案
你也可以在没有 gem 的情况下做到这一点,但使用 Rails 观察者
Also you can do this without gems but with Rails Observers
您可以像这样创建观察者:
You can create observer like this:
class UserTouchObserver < ActiveRecord::Observer
observe :product, :post, :comment
def after_create(model)
update_attribute(:created_by, current_user.id) if model.respond_to?(:created_by)
end
def after_update(model)
update_attribute(:updated_by, current_user.id) if model.respond_to?(:updated_by)
end
end
这篇关于如何实现类似于“自动插入时间戳"的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!