app/models/concerns/adminpanel/sortable.rb in adminpanel-2.4.3 vs app/models/concerns/adminpanel/sortable.rb in adminpanel-2.5.0
- old
+ new
@@ -4,61 +4,64 @@
# the lower the (position) integer is, the better it is.
included do
before_create :set_position
before_destroy :rearrange_positions
-
- default_scope do
- order('position ASC')
- end
end
module ClassMethods
def is_sortable?
true
end
- end
- def move_to_better_position
- if self.position > 1
- conflicting_gallery(self.position - 1).increment!(:position)
- self.decrement!(:position)
+ def ordered
+ order('position ASC')
+ end
- true
- else
- false
+ def in_better_position(current_position, new_position)
+ where(
+ 'position >= ? AND position < ?',
+ new_position,
+ current_position
+ )
end
+
+ def in_worst_position(current_position, new_position)
+ where(
+ 'position > ? AND position <= ?',
+ current_position,
+ new_position
+ )
+ end
end
- def move_to_worst_position
- records = self.class.count
- if self.position < records
- conflicting_gallery(self.position + 1).decrement!(:position)
- self.increment!(:position)
- true
+ def move_to_position(new_position)
+ if new_position < position
+ # search for better elements and downgrade them
+ self.class.in_better_position(
+ self.position,
+ new_position
+ ).update_all('position = position + 1')
else
- false
+ # search for worster elements and upgrade them
+ self.class.in_worst_position(
+ self.position,
+ new_position
+ ).update_all('position = position - 1')
end
+ self.update(position: new_position)
end
protected
- def conflicting_gallery(conflicting_position)
- logger.info "searching pos: #{conflicting_position}"
- self.class.find_by_position(conflicting_position)
- end
def rearrange_positions
- unarranged_records = self.class.where(
+ self.class.where(
'position > ?', self.position
- )
- unarranged_records.each do |record|
- record.update_attribute(:position, gallery.position - 1)
- end
-
+ ).update_all('position = position - 1')
end
def set_position
- last_record = self.class.last
+ last_record = self.class.ordered.last
if last_record.nil?
# this is the first record that is created
self.position = 1
else
self.position = last_record.position + 1