ruby-on-railspaper-trail-gem

Rails multiple conditions in paper-trail


what I'm trying to achieve is to only monitor versions of fields, if certain conditions are met. For example: field_a, field_b, field_c if condition_a is true, and field_d, field_e, field_f if condition_b is true.
My code in my modal is:

has_paper_trail only: [:field_a, :field_b, :field_c], if: Proc.new { |cand| cand.condition_a? }

has_paper_trail only: [:field_d, :field_e, :field_f], if: Proc.new { |cand| cand.condition_b? }

(.condition_a? and .condition_b? are private methods for my model, that returns boolean value)
But in that case only the second line of code seems to work (but is executed twice).

Is it even possible to achieve this kind of behavior?


Solution

  • According to PaperTrail's documentation (https://github.com/paper-trail-gem/paper_trail#only):

    The :ignore and :only options can also accept Hash arguments.

    Which means you can use this solution:

    has_paper_trail only: { field_a: :condition_a?, field_b: :condition_a?, field_c: :condition_a?, field_d: :condition_b?, field_e: :condition_b?, field_f: :condition_b? }
    

    (passing a symbol with method name instead of proc will work because of Ruby :to_proc method - you can read more about it in this blogpost)