after_save callback to set the updated_by column t

2020-06-17 15:06发布

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?

2条回答
放荡不羁爱自由
2楼-- · 2020-06-17 15:29

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
查看更多
Juvenile、少年°
3楼-- · 2020-06-17 15:29

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)
查看更多
登录 后发表回答