@@ -9,7 +9,11 @@ class SchoolClass < ApplicationRecord
9
9
10
10
scope :with_teachers , -> ( user_id ) { joins ( :teachers ) . where ( teachers : { id : user_id } ) }
11
11
12
+ before_validation :assign_class_code , on : :create
13
+
12
14
validates :name , presence : true
15
+ validates :code , uniqueness : { scope : :school_id } , presence : true , format : { with : /\d \d -\d \d -\d \d / , allow_nil : false }
16
+ validate :code_cannot_be_changed
13
17
validate :school_class_has_at_least_one_teacher
14
18
15
19
has_paper_trail (
@@ -36,11 +40,30 @@ def with_teachers
36
40
[ self , User . from_userinfo ( ids : teacher_ids ) ]
37
41
end
38
42
43
+ def assign_class_code
44
+ return if code . present?
45
+
46
+ 5 . times do
47
+ self . code = ForEducationCodeGenerator . generate
48
+ return if code_is_unique_within_school
49
+ end
50
+
51
+ errors . add ( :code , 'could not be generated' )
52
+ end
53
+
39
54
private
40
55
41
56
def school_class_has_at_least_one_teacher
42
57
return if teachers . present?
43
58
44
59
errors . add ( :teachers , 'must have at least one teacher' )
45
60
end
61
+
62
+ def code_cannot_be_changed
63
+ errors . add ( :code , 'cannot be changed after verification' ) if code_was . present? && code_changed?
64
+ end
65
+
66
+ def code_is_unique_within_school
67
+ code . present? && SchoolClass . where ( code :, school :) . none?
68
+ end
46
69
end
0 commit comments