mongoid-history icon indicating copy to clipboard operation
mongoid-history copied to clipboard

Adding custom attributes before save

Open amoghh opened this issue 4 years ago • 1 comments

I have a unique requirement. There is not many places i can ask this question because there is hardly any material on stackoverflow for this gem. I have added history tracking to multiple models. What i want to do is to add my custom attributes to the history record before it is created. Is there any callback method which i can use to add attributes to the @history_tracker_attributes instance variable before it gets saved. I do not want to add callbacks on the tracker class since i want to add different attributes based on the models for which history is being created.

amoghh avatar Apr 16 '20 14:04 amoghh

Does a custom changes method solve your issue?

(from the README)

class Foo
  include Mongoid::Document
  include Mongoid::History::Trackable

  attr_accessor :ip

  track_history on: [:ip], changes_method: :my_changes

  def my_changes
    unless ip.nil?
      changes.merge(ip: [nil, ip])
    else
      changes
    end
  end
end

dblock avatar Apr 16 '20 15:04 dblock