lib/paper_trail/version.rb in paper_trail-1.6.4 vs lib/paper_trail/version.rb in paper_trail-1.6.5
- old
+ new
@@ -1,9 +1,29 @@
class Version < ActiveRecord::Base
belongs_to :item, :polymorphic => true
validates_presence_of :event
+ named_scope :with_item_keys, lambda { |item_type, item_id| {
+ :conditions => { :item_type => item_type, :item_id => item_id }
+ } }
+
+ named_scope :subsequent, lambda { |version| {
+ :conditions => ["id > ?", version.is_a?(ActiveRecord::Base) ? version.id : version],
+ :order => "id ASC",
+ } }
+
+ named_scope :preceding, lambda { |version| {
+ :conditions => ["id < ?", version.is_a?(ActiveRecord::Base) ? version.id : version],
+ :order => "id DESC",
+ } }
+
+ named_scope :after, lambda { |timestamp| {
+ :conditions => ['created_at > ?', timestamp],
+ # TODO: is this :order necessary, considering its presence on the has_many :versions association?
+ :order => 'created_at ASC, id ASC'
+ } }
+
# Restore the item from this version.
#
# This will automatically restore all :has_one associations as they were "at the time",
# if they are also being versioned by PaperTrail. NOTE: this isn't always guaranteed
# to work so you can either change the lookback period (from the default 3 seconds) or
@@ -67,22 +87,23 @@
# This is an alias for `whodunnit`.
def terminator
whodunnit
end
+ def sibling_versions
+ Version.with_item_keys(item_type, item_id)
+ end
+
def next
- Version.first :conditions => ["id > ? AND item_type = ? AND item_id = ?", id, item_type, item_id],
- :order => 'id ASC'
+ sibling_versions.subsequent(self).first
end
def previous
- Version.first :conditions => ["id < ? AND item_type = ? AND item_id = ?", id, item_type, item_id],
- :order => 'id DESC'
+ sibling_versions.preceding(self).first
end
def index
- Version.all(:conditions => ["item_type = ? AND item_id = ?", item_type, item_id],
- :order => 'id ASC').index(self)
+ sibling_versions.all(:select => :id, :order => "id ASC").map(&:id).index(self.id)
end
private
# Restore the `model`'s has_one associations as they were when this version was