开发者

How can I achieve a functionality similar to "auto-insertion of timestamps"

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜