I use a after_create
call back to calculate the penalty of a submitted HomeworkDocument
, based on the deadline of the Assignment
that HomeworkDocument
belongs_to
.
我使用after_create回调来计算提交的HomeworkDocument的惩罚,基于HomeworkDocument belongs_to的赋值的截止日期。
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
Everything works fine in my spec as well as when I create HomeworkDocument
one at a time in the console. However, when using loop (e.g. to populate sample data), the call back seems to be bypassed as all of the homework documents have penalty: nil
.
在我的规范中以及在控制台中一次创建一个HomeworkDocument时,一切正常。但是,当使用循环(例如填充样本数据)时,似乎绕过了回调,因为所有的家庭作业文件都有惩罚:零。
The loop is very straightforward:
循环非常简单:
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
Is this expected? If so, how do I create my sample data with the after_create
call back properly applied?
这是预期的吗?如果是这样,如何在正确应用after_create回调的情况下创建示例数据?
1 个解决方案
#1
0
You just need to a add a call to save
the instance of the HomeworkDocument
, so use self.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
#1
0
You just need to a add a call to save
the instance of the HomeworkDocument
, so use self.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