Ruby on rails 未触发删除回调后/之前的Mongoid
我认为课堂模型和学生模型之间存在以下关系:Ruby on rails 未触发删除回调后/之前的Mongoid,ruby-on-rails,callback,mongoid,Ruby On Rails,Callback,Mongoid,我认为课堂模型和学生模型之间存在以下关系: 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.stu
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代码>在我的教室模型中,在移除之前从不触发。
我试着用下面的方式编写销毁操作,以便在课堂实例上执行销毁操作,但似乎销毁不能用这种方式用于mongoid
def destroy
student = Student.find params[:id]
classroom= student.classroom
student.destroy!
classroom.students.destroy(student)
redirect_to action: :index
end
为什么我的before\u remove回调从未执行过?请在销毁之前尝试。
以下是回调的文档只是为了刷新teddybear的解决方案,我认为您可以这样做:
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