不会触发Mongoid after / before_remove回调

问题描述 投票:0回答:2

我在课堂和学生模型之间有以下关系:

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回调从未执行过?

ruby-on-rails callback mongoid
2个回答
0
投票

试试before_destroy吧。这是用于回调的Mongoid文档


0
投票

只是为了清除泰迪熊的解决方案,我想你可以这样做:

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
© www.soinside.com 2019 - 2024. All rights reserved.