我在课堂和学生模型之间有以下关系:
Classroom has_many :students
Student belongs_to :classroom
在我的课堂模型中,我有这些关系回调:
has_many :students,
after_add: :update_student_count,
before_remove: :update_student_count
def update_student_count(student)
self.student__count = students.count
self.save
end
在我的学生控制器中,我有:
def destroy
student = Student.find params[:id]
student.destroy!
redirect_to action: :index
end
然而,student.destroy!
从未在我的课堂模型中触发before_remove
回调。我已经尝试用以下方式编写动作destroy来执行教室实例上的destroy动作但是似乎无法以这种方式使用mongoid ...
def destroy
student = Student.find params[:id]
classroom= student.classroom
student.destroy!
classroom.students.destroy(student)
redirect_to action: :index
end
为什么我的before_remove回调从未执行过?
试试before_destroy
吧。这是用于回调的Mongoid文档
只是为了清除泰迪熊的解决方案,我想你可以这样做:
class Student
belongs_to :classroom
after_destroy :update_student_count
after_create :update_student_count
def update_student_count
classroom.update_student_count
end
end
class Classroom
has_many :students
def update_student_count
self.student__count = students.count
save
end
end