mongoid / mongoid-history

Multi-user non-linear history tracking, auditing, undo, redo for mongoid.
https://rubygems.org/gems/mongoid-history
MIT License
393 stars 129 forks source link

Adding custom attributes before save #241

Open amoghh opened 4 years ago

amoghh commented 4 years ago

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.

dblock commented 4 years ago

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