From c4e7b3c74477a83220950a2921ac4dcc36719ae4 Mon Sep 17 00:00:00 2001 From: Owen Rodda Date: Sat, 16 Jan 2016 21:48:48 -0500 Subject: [PATCH] Default order by timestamp to ensure early versions are cleaned --- CHANGELOG.md | 5 ++++- lib/paper_trail/cleaner.rb | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a863c4a..c31b1a65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,10 @@ None ### Fixed -None +- [#701](https://github.com/airblade/paper_trail/pull/701) / + [#699](https://github.com/airblade/paper_trail/issues/699) - + Cleaning old versions explicitly preserves the most recent + versions instead of relying on database result ordering. ## 4.1.0 (Unreleased) diff --git a/lib/paper_trail/cleaner.rb b/lib/paper_trail/cleaner.rb index d4c59316..69273eac 100644 --- a/lib/paper_trail/cleaner.rb +++ b/lib/paper_trail/cleaner.rb @@ -6,7 +6,8 @@ module PaperTrail # Options: # # - :keeping - An `integer` indicating the number of versions to be kept for - # each item per date. Defaults to `1`. + # each item per date. Defaults to `1`. The most recent matching versions + # are kept. # - :date - Should either be a `Date` object specifying which date to # destroy versions for or `:all`, which will specify that all dates # should be cleaned. Defaults to `:all`. @@ -30,12 +31,14 @@ module PaperTrail # Returns a hash of versions grouped by the `item_id` attribute formatted # like this: {:item_id => PaperTrail::Version}. If `item_id` or `date` is # set, versions will be narrowed to those pointing at items with those ids - # that were created on specified date. + # that were created on specified date. Versions are returned in + # chronological order. def gather_versions(item_id = nil, date = :all) unless date == :all || date.respond_to?(:to_date) raise ArgumentError.new("`date` argument must receive a Timestamp or `:all`") end versions = item_id ? PaperTrail::Version.where(:item_id => item_id) : PaperTrail::Version + versions = versions.order(PaperTrail.timestamp_field, :id) versions = versions.between(date.to_date, date.to_date + 1.day) unless date == :all # If `versions` has not been converted to an ActiveRecord::Relation yet,