0

我有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"}

我错了什么?

4

2 回答 2

11

self.save最后打了电话。它正在开始另一个after_save回调。

如果您的 rails 版本是 3.2.1 或更高版本,您可以使用

update_column :number_question, number_question

跳过回调。

题外话:

你可以重写它

number_question = 0
self.topic_questions.each do  |tq|
  number_question += tq.number_question
end

作为

number_question = self.topic_questions.inject(0) { |sum, tq| sum + tq.number_question }
于 2012-11-22T15:44:19.697 回答
0

用作after_commit回调。从那以后它就可以正常工作了,它不会循环。

于 2013-12-29T01:20:04.187 回答