-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathschool_class.rb
More file actions
80 lines (59 loc) · 2.23 KB
/
school_class.rb
File metadata and controls
80 lines (59 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# frozen_string_literal: true
class SchoolClass < ApplicationRecord
belongs_to :school
has_many :students, class_name: :ClassStudent, inverse_of: :school_class, dependent: :destroy
has_many :teachers, class_name: :ClassTeacher, inverse_of: :school_class, dependent: :destroy
has_many :lessons, dependent: :nullify
accepts_nested_attributes_for :teachers
scope :with_teachers, ->(user_id) { joins(:teachers).where(teachers: { id: user_id }) }
before_validation :assign_class_code, on: %i[create import]
validates :name, presence: true
validates :code, uniqueness: { scope: :school_id }, presence: true, format: { with: /\d\d-\d\d-\d\d/, allow_nil: false }
validate :code_cannot_be_changed
validate :school_class_has_at_least_one_teacher
enum :import_origin, { google_classroom: 0 }, validate: { allow_nil: true }
validates :import_origin, presence: true, on: :import
validates :import_id, presence: true, on: :import
validates :import_id, uniqueness: { scope: %i[school_id import_origin] }, if: -> { import_id.present? }
has_paper_trail(
meta: {
meta_school_id: ->(cm) { cm.school&.id }
}
)
def self.teachers
teacher_ids = all.map(&:teacher_ids).flatten.uniq
User.from_userinfo(ids: teacher_ids)
end
def self.with_teachers
by_id = teachers.index_by(&:id)
all.map { |instance| [instance, instance.teacher_ids.map { |teacher_id| by_id[teacher_id] }] }
end
def teacher_ids
teachers.pluck(:teacher_id)
end
def with_teachers
[self, User.from_userinfo(ids: teacher_ids)]
end
def assign_class_code
return if code.present?
5.times do
self.code = ForEducationCodeGenerator.generate
return if code_is_unique_within_school?
end
errors.add(:code, 'could not be generated')
end
def submitted_projects_count
lessons.to_a.sum(&:submitted_projects_count)
end
private
def school_class_has_at_least_one_teacher
return if teachers.present?
errors.add(:teachers, 'must have at least one teacher')
end
def code_cannot_be_changed
errors.add(:code, 'cannot be changed after verification') if code_was.present? && code_changed?
end
def code_is_unique_within_school?
code.present? && SchoolClass.where(code:, school:).none?
end
end