HMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered

前端 未结 3 705
梦如初夏
梦如初夏 2021-02-06 02:24

Just ran into an issue with a has_many :through association and after/before-destroy callbacks not being triggered.

Say, I have users, groups, and an intermediate relati

3条回答
  •  轮回少年
    2021-02-06 02:47

    I've struggled with the same problem recently and solved it by extending association and overriding its delete method:

    class User < ActiveRecord::Base
      has_many :memberships
      has_many :groups, :through => :memberships do
        def delete(*args)
          groups = args.flatten
          # destroy memberships in order to trigger their callbacks:
          proxy_association.owner.memberships.where(group_id: groups).destroy_all
          super
        end
      end
      ...
    end
    

提交回复
热议问题