diff --git a/app/models/object_manager/attribute.rb b/app/models/object_manager/attribute.rb index 962796ca1..88ea4fac5 100644 --- a/app/models/object_manager/attribute.rb +++ b/app/models/object_manager/attribute.rb @@ -26,6 +26,7 @@ class ObjectManager::Attribute < ApplicationModel validates :name, presence: true validates :data_type, inclusion: { in: DATA_TYPES, msg: '%{value} is not a valid data type' } # rubocop:disable Style/FormatStringToken + validate :inactive_must_be_unused_by_references, unless: :active? validate :data_option_must_have_appropriate_values validate :data_type_must_not_change, on: :update @@ -844,6 +845,16 @@ is certain attribute used by triggers, overviews or schedulers .each { |validation| errors.add(local_data_attr, validation[:message]) } end + def inactive_must_be_unused_by_references + return if !ObjectManager::Attribute.attribute_used_by_references?(object_lookup.name, name) + + human_reference = ObjectManager::Attribute.attribute_used_by_references_humaniced(object_lookup.name, name) + text = "#{object_lookup.name}.#{name} is referenced by #{human_reference} and thus cannot be set to inactive!" + + # Adding as `base` to prevent `Active` prefix which does not look good on error message shown at the top of the form. + errors.add(:base, text) + end + def data_type_must_not_change allowable_changes = %w[tree_select select input checkbox] diff --git a/spec/models/object_manager/attribute_spec.rb b/spec/models/object_manager/attribute_spec.rb index a5ce46fdc..870d59993 100644 --- a/spec/models/object_manager/attribute_spec.rb +++ b/spec/models/object_manager/attribute_spec.rb @@ -107,4 +107,43 @@ RSpec.describe ObjectManager::Attribute, type: :model do end.not_to raise_error end end + + describe 'validate that referenced attributes are not set as inactive' do + subject(:attr) { create(:object_manager_attribute_text) } + + before do + allow(described_class) + .to receive(:attribute_used_by_references?) + .with(attr.object_lookup.name, attr.name) + .and_return(is_referenced) + + attr.active = active + end + + context 'when is used and changing to inactive' do + let(:active) { false } + let(:is_referenced) { true } + + it { is_expected.not_to be_valid } + + it do + attr.valid? + expect(attr.errors).not_to be_blank + end + end + + context 'when is not used and changing to inactive' do + let(:active) { false } + let(:is_referenced) { false } + + it { is_expected.to be_valid } + end + + context 'when is used and staying active and chan' do + let(:active) { true } + let(:is_referenced) { true } + + it { is_expected.to be_valid } + end + end end