After that, it sets a few
variables. It finds the appropriate TrainingClass, which the user has selected using a
drop-down list, and then parses the user-entered date. These variables will be used to
assign a date and a TrainingClass to each grade entered on the form.
Next, you loop through the params[:trainee] array, which has one entry for each row
of your form, and add a grade object for each of them:
params[:trainee].each do |index, t|
next if t[:name]==''
student = Student.find_or_create_by_name_and_employer( t[:name],
t[:employer])
student.grades.create(:percentage_grade => t[:grade],
:training_class=>training_class,
:took_class_at=>training_class_date)
count = count +1
end
flash[:notice]="#{count} Entries Uploaded!"
end
end
Note the use of find_or_create_by_name_and_employer. This dynamically generated
finder returns an existing Student object with that name and employer if it already exists;
if not, it creates a new one.
nNote Using the dynamically generated finder means that a typo in the name or employer field will create
a new Student record, which may be a problem.
Pages:
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356