class ChecklistEntry < ApplicationRecord belongs_to :checklist belongs_to :check before_validation :set_position after_validation :normalize_positions def set_position self.position ||= checklist.checklist_entries.maximum(:position).to_i + 1 end def normalize_positions checklist.checklist_entries.where.not(id:).find_by(position:)&.update_attribute(:position, position_was) # checklist.checklist_entries.order(:position).each_with_index do |entry, index| # entry.update_column(:position, index + 1) if entry.position != index + 1 # end end end