我有2个模型:
- GeneralExam有很多TopicQuestion
- TopicQuestion 属于 GeneralExam,belongs_to Topic
这是两个模型中的列:
- GeneralExam:名称,描述,number_question
- 主题问题:general_exam_id、topic_id、number_question
我想通过加上 TopicQuestion 中每个主题的 number_question 来计算一般考试的问题总数。所以我写了一个这样的方法:
class GeneralExam < ActiveRecord::Base
has_many :topic_questions, dependent: :destroy
validates :number_question, numericality: { only_integer: true, greater_than: 0 }, on: :save
after_save :calc_number_question
private
def calc_number_question
number_question = 0
self.topic_questions.each do |tq|
number_question += tq.number_question
end
self.number_question = number_question
self.save
end
end
但是当我提交时,我收到错误:
SystemStackError in GeneralExamsController#create
stack level too deep
这是我的参数:
{"utf8"=>"✓",
"authenticity_token"=>"VyojDMOltc5wOJMDf4gtDM6lEk6soTZl/EaY9qrCRyY=",
"general_exam"=>{"course_id"=>"1",
"name"=>"dada",
"description"=>"dada",
"semester_id"=>"1",
"duration"=>"1",
"topic_questions_attributes"=>{"0"=>{"_destroy"=>"false",
"topic_id"=>"15",
"number_question"=>"15"},
"1"=>{"_destroy"=>"false",
"topic_id"=>"13",
"number_question"=>"6"},
"2"=>{"_destroy"=>"false",
"topic_id"=>"Choose a topic",
"number_question"=>""},
"3"=>{"_destroy"=>"false",
"topic_id"=>"Choose a topic",
"number_question"=>""},
"4"=>{"_destroy"=>"false",
"topic_id"=>"Choose a topic",
"number_question"=>""}}},
"commit"=>"Create General exam"}
我错了什么?