diff --git a/app/models/my_module.rb b/app/models/my_module.rb index 482e538ee..96f7c3a3c 100644 --- a/app/models/my_module.rb +++ b/app/models/my_module.rb @@ -17,7 +17,7 @@ class MyModule < ApplicationRecord validates :experiment, presence: true validates :my_module_group, presence: true, if: proc { |mm| !mm.my_module_group_id.nil? } - validates_uniqueness_of :x, scope: %i(y experiment_id), message: :not_unique + validate :coordinates, if: proc { |mm| !mm.archived? } belongs_to :created_by, foreign_key: 'created_by_id', @@ -501,4 +501,12 @@ class MyModule < ApplicationRecord def create_blank_protocol protocols << Protocol.new_blank_for_module(self) end + + def coordinates + my_modules_on_same_position = + MyModule.where(experiment_id: experiment_id, x: x, y: y, archived: false).where.not(id: id) + if my_modules_on_same_position.any? + errors.add(:position, I18n.t('activerecord.errors.models.my_module.attributes.position.not_unique')) + end + end end diff --git a/config/locales/en.yml b/config/locales/en.yml index 425d4cc46..b127c0e6e 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -83,15 +83,14 @@ en: same_team: "Inventory can't be shared to the same team as it belongs to" my_module: attributes: - x: - not_unique: "and Y position has already been taken by another task in the experiment." + position: + not_unique: "X and Y position has already been taken by another task in the experiment." asset: attributes: file: too_big: "is too big" - helpers: label: team: diff --git a/spec/models/my_module_spec.rb b/spec/models/my_module_spec.rb index 9b918eb20..56e33e591 100644 --- a/spec/models/my_module_spec.rb +++ b/spec/models/my_module_spec.rb @@ -79,15 +79,23 @@ describe MyModule, type: :model do end end - describe '#x, #y scoped to experiment' do + describe '#x, #y scoped to experiment for active modules' do it { is_expected.to validate_presence_of :x } it { is_expected.to validate_presence_of :y } - it do - expect(my_module) - .to(validate_uniqueness_of(:x) - .scoped_to(%i(y experiment_id)) - .with_message('and Y position has already been taken by another task in the experiment.')) + it 'should be invalid for same x, y, and experiment' do + my_module.save + new_my_module = my_module.dup + + expect(new_my_module).not_to be_valid + end + + it 'should be valid when module with same x, y and expriment is archived' do + my_module.save + new_my_module = my_module.dup + my_module.update_column(:archived, true) + + expect(new_my_module).to be_valid end end