after_create不会在数据库中创建更改

时间:2014-06-06 18:18:42

标签: ruby-on-rails

根据after_create HomeworkDocument Assignment的截止日期,我使用HomeworkDocument来回计算已提交的belongs_to的点球。 / p>

  class HomeworkDocument < ActiveRecord::Base

  after_create :calculate_penalty
  private

    def calculate_penalty
      time_late = created_at - assignment.deadline
      case
      when time_late < 0
        self.penalty = 0
      when time_late > 1.day
        self.penalty = 1
      end
    end

在我的规范中以及在控制台中一次创建一个HomeworkDocument时,一切正常。但是,当使用循环(例如填充样本数据)时,似乎绕过了回调,因为所有家庭作业文档都有penalty: nil

循环非常简单:

   Student.all.each do |student|
      Assignment.all.each do |assignment|
        student.submitted_homework_documents.create(
          assignment_id: assignment.id,
          created_at: rand(-1.month..1.month).ago)
      end
   end

这是预期的吗?如果是这样,如何在正确应用after_create回拨的情况下创建示例数据?

1 个答案:

答案 0 :(得分:0)

您只需要save添加对HomeworkDocument实例的调用,所以请使用self.save

def calculate_penalty
  time_late = created_at - assignment.deadline
  case
  when time_late < 0
    self.penalty = 0
  when time_late > 1.day
    self.penalty = 1
  end
  self.save
end