class CourseAttendance < ApplicationRecord # mode: 0 两种签到,1 二维码签到,2 数字签到 belongs_to :course belongs_to :user has_many :course_attendance_groups, dependent: :destroy has_many :course_member_attendances, dependent: :destroy validates :name, presence: true validates :mode, presence: true validates :attendance_date, presence: true validates :start_time, presence: true validates :end_time, presence: true after_create :generate_attendance_code # 延迟生成邀请码 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