my classroom
model has 2 attributes, student_classcode
, teacher_classcode
. have after_create
callback generate these 2 codes after classroom created. currently, generate student_classcode far this:
(taken here)
class classroom < activerecord::base after_create :generate_token private max_retries = 10 def generate_token update_column :student_classcode, securerandom.hex(4) rescue activerecord::recordnotunique => e @token_attempts = @token_attempts.to_i + 1 retry if @token_attempts < max_retries raise e, "retries exhausted" end end
right makes sure student_classcode
unique (with 10 retries). want able generate teacher_classcode
well, , want make sure unique among teacher_classcode
column and student_classcode
column.
so example, if classroom has student_classcode
'12345', , (by chance) teacher_classcode
of classroom b generates '12345', want classroom b regenerate classcode. or, if classroom b has student_classcode
'abcde', , classroom b has teacher_classcode
'abcde', want classroom b regenerate teacher_classcode
.
i know chances of there being 2 of same classcode across both columns small, don't want take chances. how can that?
why don't make classcode
model in own right, validations ensure code unique. generate generic code , through standard belongs_to
associations classroom
can associate teacher , student classcode.
this way can sure each classcode unique , have 1 implementation of code generation.
Comments
Post a Comment