2022-04-19 04:38:49 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class StepOrderableElement < ApplicationRecord
|
|
|
|
validates :position, uniqueness: { scope: :step }
|
|
|
|
validate :check_step_relations
|
|
|
|
|
|
|
|
around_destroy :decrement_following_elements_positions
|
|
|
|
|
2022-04-29 18:29:42 +08:00
|
|
|
belongs_to :step, inverse_of: :step_orderable_elements, touch: true
|
2022-07-20 16:14:48 +08:00
|
|
|
belongs_to :orderable, polymorphic: true, inverse_of: :step_orderable_element
|
2022-04-19 04:38:49 +08:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def check_step_relations
|
|
|
|
if step != orderable.step
|
|
|
|
errors.add(
|
|
|
|
:step_orderable_element,
|
2022-07-06 17:45:04 +08:00
|
|
|
I18n.t('activerecord.errors.models.step_orderable_element.attributes.step.wrong_step')
|
2022-04-19 04:38:49 +08:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def decrement_following_elements_positions
|
|
|
|
step.with_lock do
|
|
|
|
yield
|
2023-08-21 15:22:56 +08:00
|
|
|
step.normalize_elements_position
|
2022-04-19 04:38:49 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|