I have a couple o开发者_如何学JAVAf 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?
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
I was able to find a few plugins on github that do just this:
- https://github.com/jnunemaker/user_stamp
- https://github.com/bokmann/userstamp_basic
精彩评论