Search code examples
ruby-on-railsruby-on-rails-3.1ruby-on-rails-plugins

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


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?


Solution

  • 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