ruby-on-railspaper-trail-gem

Rails 6 PaperTrail pull logs from only one model


Let's assume I'm tracking two models in my Rails 6 app using PaperTrail gem - Book and User. Now I want to generate CSV file with logs only which includes only Book models activities. How to how to pull versions for only one model e.g. Book ?

# models
class Book
  has_paper_trail
end

class User
  has_paper_trail
end

#call method for csv_generator service

    def call
      CSV.generate(col_sep: ';', write_headers: true, headers: LOG_HEADERS, encoding: 'UTF-8') do |csv|
        PaperTrail::Version.includes([:item]).limit(50).order(id: :desc).each do |v|
          tracked_data(v)
          csv << [v.created_at.in_time_zone('CET'),
                  v.event,
                  version.whodunnit,
                  @new_data_value]
        end
      end
    end

Now I get logs from both Book and User models instead of only Book.


Solution

  • The default migration adds an item_type column which is used to track the tables.

    In the given case you can do: PaperTrail::Version.where(item_type: 'Book') which will find you all versions for all changes in the book table.

    If you want to do per instance of book it would be just:

    Book.all.each do |book|
      book.versions
    end