I'm new to rails and I can think of several ways to solve this problem, but I'd like to do it the "rails" way. My problem is that I have a model - exam - which :has_many questions. I'd like to write a function in the exam model which will calculate the score for the exam (and store it in the exam model). To do this, I need to read data from the question objects that belong to the exam.
Any tips or links to documentation would be开发者_Go百科 greatly appreciated.
As far as you didn't write anything about your data structure let's imagine that your every question has_got Boolean correct
field. And your exam has got Integer total_score
field. So after examing it should count all questions with correct answer:
class Exam < ActiveRecord::Base
has_many :questions
before_save :set_score
def set_score
total_score = questions.where(:correct => true).count
end
end
精彩评论