根据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
回拨的情况下创建示例数据?
答案 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