before_destroy 没有触发 has_many :through

before_destroy not firing with has_many :through

我想删除 group_maps 中与被销毁的组关联的所有记录。 In the docs,上面写着

If the :through option is used, then the join records are destroyed instead, not the objects themselves.

我很困惑。

group.rb

class Group < ApplicationRecord

  belongs_to :user

  has_many :group_maps
  has_many :users, :through => :group_maps

  before_destroy :destroy_group_maps

  def destroy_group_maps
    self.group_maps.delete_all
  end

end

编辑 1:
顺便说一下,我试过添加 , :dependent => destroy:dependent => delete_all 还有。 None 其中有效果。

编辑 2:
group_maps_controller.rb

class GroupMapsController < ApplicationController

  def destroy
    GroupMap.find[params[:id]].destroy
  end
end

在您的 destroy_group_maps 方法中,键入:

def destroy_group_maps
  self.group_maps.each { |group_map| group_map.destroy }
end

您可以添加 dependent: :destroy 来删除关联,而不是调用 before_destroy 来破坏关联。

dependent: :destroy 删除关联记录,一旦父记录被删除。

我更喜欢使用 dependent: :destroy 而不是 before_destroy

class Group < ApplicationRecord

  belongs_to :user

  has_many :group_maps, dependent: :destroy
  has_many :users, :through => :group_maps

  before_destroy :destroy_group_maps

  def destroy_group_maps
    self.group_maps.delete_all
  end

end