21 lines
619 B
Ruby
21 lines
619 B
Ruby
# frozen_string_literal: true
|
|
|
|
class ChecklistEntry < ApplicationRecord
|
|
belongs_to :checklist
|
|
belongs_to :check
|
|
|
|
before_validation :set_position
|
|
before_create :update_positions
|
|
before_update :update_positions, if: :position_changed?
|
|
|
|
def set_position
|
|
self.position ||= (checklist.checklist_entries.pluck(:position).max || 0) + 1
|
|
end
|
|
|
|
def update_positions
|
|
if position_was
|
|
checklist.checklist_entries.where("position > ?", position_was).update_all("position = position - 1")
|
|
end
|
|
checklist.checklist_entries.where(position: position..).update_all("position = position + 1")
|
|
end
|
|
end
|