首页 > 解决方案 > 如何解决 []= 删除中间关系栏

问题描述

我将通过下一个示例模拟我的问题,假设我有student可能与 s 相关的courses,并且course包含多个s student。因此,学生和课程之间是多对多的关系,考虑以下代码:

# student.rb
class Student < ApplicationRecord
  has_many :student_courses
  has_many :courses, through: :student_courses
end
# student_course.rb
class StudentCourse < ApplicationRecord
  belong_to :student
  belong_to :course
end
# course.rb
class Course < ApplicationRecord
  has_many :student_courses
  has_many :students, through: :student_courses
end

以上所有内容都可以,但是当我试图在这些关系之间进行删除并在中间表中进行回调时


> c = Course.first
> c.students = [] # this perform a deletion correctly but can't be triggered by a call back

makestudents和空数组正确删除了关系,但它不是由回调触发的。使用StudentCenter.where(something).destroy_all时会触发after_destroy等。

我的问题是,我怎么能使用= []并保持触发,因为我发现中间桌子上的操作在阅读代码时有点吵。提前致谢。

标签: ruby-on-railsrubyactiverecord

解决方案


推荐阅读