Reputation: 4813
Is there a way to limit the number of versions, per model, in Papertrail?
E.g., I know I can set a global limit with
PaperTrail.config.version_limit = 3
But I don't see a way to set that per model, with something like
class Article < ActiveRecord::Base
has_paper_trail :limit => [10]
end
I also don't want to just limit the number of versions saved (to say ten) but have it so only the latest ten are saved (same as with the config
version setting).
Upvotes: 1
Views: 1533
Reputation: 2277
As for Paper Trail 11.0.0, limiting the number of versions created supported by gem out from the box: https://github.com/paper-trail-gem/paper_trail#2e-limiting-the-number-of-versions-created
For example:
# At most 3 versions (2 updates, 1 create). Overrides global version_limit.
has_paper_trail limit: 2
Upvotes: 2
Reputation: 1055
Here is the answer you want:
Add constant "PAPER_TRAIL_VERSION_LIMIT" to your Article model like below
# models/article.rb
class Article < ActiveRecord::Base
has_paper_trail
# 10 mean you article will have 11 version include 'create' version
PAPER_TRAIL_VERSION_LIMIT = 10
end
Add below codes to the bottom of PaperTrail config file
# /config/initializers/paper_trail.rb
module PaperTrail
class Version < ActiveRecord::Base
private
def enforce_version_limit!
limit = PaperTrail.config.version_limit
# This is the key custom line
limit = item.class::PAPER_TRAIL_VERSION_LIMIT if item.class.const_defined?("PAPER_TRAIL_VERSION_LIMIT")
return unless limit.is_a? Numeric
previous_versions = sibling_versions.not_creates
return unless previous_versions.size > limit
excess_versions = previous_versions - previous_versions.last(limit)
excess_versions.map(&:destroy)
end
end
end
Enjoy it ! :D
Upvotes: 7
Reputation: 5983
Add the following initializer:
# /config/initializers/paper_trail.rb
module PaperTrail
module VersionConcern
private
def enforce_version_limit!
limit = defined?(version_limit) ? version_limit : PaperTrail.config.version_limit
return unless limit.is_a? Numeric
previous_versions = sibling_versions.not_creates
return unless previous_versions.size > limit
excess_versions = previous_versions - previous_versions.last(limit)
excess_versions.map(&:destroy)
end
end
end
Then you can simply define version_limit
in any model you want to specify an alternative limit for.
def version_limit
20
end
Upvotes: 1
Reputation: 11235
Consider using the if:
syntax to selectively turn off paper trail:
has_paper_trail :if => Proc.new { |model| model.versions.count > 10 }
Specifics from the docs: https://github.com/airblade/paper_trail#choosing-when-to-save-new-versions
Upvotes: -1