diff --git a/app/models/lessons_validator.rb b/app/models/lessons_validator.rb index 1c068c4..6685995 100644 --- a/app/models/lessons_validator.rb +++ b/app/models/lessons_validator.rb @@ -7,6 +7,7 @@ def validate_each(record, attribute, value) check_correct_class(record, attribute, value) check_unique_refs(record, attribute, value) + check_unique_title(record, attribute, value) end def check_correct_class(record, attribute, value) @@ -26,4 +27,16 @@ def check_unique_refs(record, attribute, value) non_unique_refs.each { |ref| record.errors.add(attribute, "(#{lesson.title}) segment ref #{ref} is not unique") } end end + + def check_unique_title(record, attribute, value) + return unless value.is_a?(Array) + + value.each do |lesson| + title_counts = Hash.new(0) + lesson.segments.each { |segment| title_counts[segment.title] += 1 } + non_unique_titles = title_counts.select { |_, count| count > 1 }.keys + + non_unique_titles.each { |title| record.errors.add(attribute, "(#{lesson}) segment title #{title} is not unique") } + end + end end