开发者

How do I calculate a value in a model based on children of that model in rails3?

开发者 https://www.devze.com 2023-02-20 02:54 出处:网络
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 wr

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
0

精彩评论

暂无评论...
验证码 换一张
取 消