After_save callback to set the updated_by column to current_user

I would like to use the after_save callback to set the updated_by column to current_user. But current_user is not available in the model. How can I do it?

+6
source share
2 answers

You need to process it in the controller. First save to the model, and then successfully update the recording field.

Example

class MyController < ActionController::Base def index if record.save record.update_attribute :updated_by, current_user.id end end end 

Another option (I prefer this) is to create your own method in your model that wraps the logic. for instance

 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 
+8
source

I implemented this monkeypatch based on the advice of Simone Carletti, as far as I could tell, touch only has timestamps, not user identifiers. Is there something wrong with this? This is intended to work with the current_user device.

 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 them like this:

 @foo.save_with_user(current_user) @foo.update_attributes_with_user(params[:foo], current_user) 
+1
source

Source: https://habr.com/ru/post/895710/


All Articles