class CourseAttendance < ApplicationRecord # status: 0: 未开启,1:已开启,2:已截止 # mode: 0 两种签到,1 二维码签到,2 数字签到,3 快捷签到 enum mode: { ALL: 0, QRCODE: 1, NUMBER: 2, QUICK: 3 } belongs_to :course belongs_to :user has_many :course_attendance_groups, dependent: :destroy has_many :course_member_attendances, dependent: :destroy has_one :course_act, class_name: 'CourseActivity', as: :course_act, dependent: :destroy validates :name, presence: true, length: { maximum: 60, too_long: "不能超过60个字符" } validates :mode, presence: true validates :attendance_date, presence: true validates :start_time, presence: true validates :end_time, presence: true after_create :generate_attendance_code, :act_as_course_activity # 正常签到人数 def normal_count course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "NORMAL"}.size end # 请假人数 def leave_count course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "LEAVE"}.size end # 旷课人数 def absence_count course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "ABSENCE"}.size end # 总人数 def all_count course_member_attendances.size end def current_attendance? a_start_time = "#{attendance_date} #{start_time}".to_time a_end_time = "#{attendance_date} #{end_time}".to_time a_start_time < Time.current && Time.current < a_end_time end #课程动态公共表记录 def act_as_course_activity CourseActivity.create(user_id: user_id, course_id: course_id, course_act: self) end # 延迟生成邀请码 def attendance_code return generate_attendance_code end # 生成邀请码 CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z) def generate_attendance_code code = read_attribute(:attendance_code) if !code || code.size < 4 code = CODES.sample(4).join return generate_attendance_code if CourseAttendance.where(attendance_code: code).present? update_attribute(:attendance_code, code) end code end end