Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after_save callback to set the updated_by column to the 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?

like image 952
pixelearth Avatar asked Aug 23 '11 21:08

pixelearth


2 Answers

You need to handle it in the controller. First execute the save on the model, then if successful update the record field.

Example

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
like image 191
Simone Carletti Avatar answered Sep 29 '22 00:09

Simone Carletti


I have implemented this monkeypatch based on Simone Carletti's advice, as far as I could tell touch only does timestamps, not the users id. Is there anything wrong with this? This is designed to work with a devise current_user.

class ActiveRecord::Base
  def save_with_user(user)
    self.updated_by_user = user unless user.blank?
    save
  end 

  def update_attributes_with_user(attributes, user)
    self.updated_by_user = user unless user.blank?
    update_attributes(attributes)
  end  
end

And then the create and update methods call these like so:

@foo.save_with_user(current_user)
@foo.update_attributes_with_user(params[:foo], current_user)
like image 22
Matt Avatar answered Sep 29 '22 01:09

Matt