Add uniqueness to sample_type & sample_group name

Closes SCI-720.
This commit is contained in:
Luka Murn 2016-11-25 15:53:44 +01:00
parent 5b917768a7
commit 7658ae264a
3 changed files with 50 additions and 2 deletions

View file

@ -2,7 +2,8 @@ class SampleGroup < ActiveRecord::Base
auto_strip_attributes :name, :color, nullify: false
validates :name,
presence: true,
length: { maximum: Constants::NAME_MAX_LENGTH }
length: { maximum: Constants::NAME_MAX_LENGTH },
uniqueness: { scope: :organization, case_sensitive: false }
validates :color,
presence: true,
length: { maximum: Constants::COLOR_MAX_LENGTH }

View file

@ -2,7 +2,8 @@ class SampleType < ActiveRecord::Base
auto_strip_attributes :name, nullify: false
validates :name,
presence: true,
length: { maximum: Constants::NAME_MAX_LENGTH }
length: { maximum: Constants::NAME_MAX_LENGTH },
uniqueness: { scope: :organization, case_sensitive: false }
validates :organization, presence: true
belongs_to :created_by, foreign_key: 'created_by_id', class_name: 'User'

View file

@ -0,0 +1,46 @@
class RenameNonUniqueSampleTypesGroups < ActiveRecord::Migration
def up
Organization.find_each do |org|
st_ids = []
org.sample_types.find_each do |st|
if SampleType.where(organization_id: org.id)
.where(name: st.name).count > 1
st_ids << st.id
end
end
next if st_ids.count == 0
cntr = -1
SampleType.where(id: st_ids).find_each do |st|
cntr += 1
next if cntr == 0
new_name = "#{st.name} (#{cntr})"
st.update(name: new_name)
end
end
Organization.find_each do |org|
sg_ids = []
org.sample_groups.find_each do |sg|
if SampleGroup.where(organization_id: org.id)
.where(name: sg.name).count > 1
sg_ids << sg.id
end
end
next if sg_ids.count == 0
cntr = -1
SampleGroup.where(id: sg_ids).find_each do |sg|
cntr += 1
next if cntr == 0
new_name = "#{sg.name} (#{cntr})"
sg.update(name: new_name)
end
end
end
def down
end
end