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

前端 未结 3 673
梦如初夏
梦如初夏 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:45

    adding dependent: :destroy to the has many relationship actually calls the before_destroy and after_destroy methods in the Membership class.

    class User < ActiveRecord::Base
      has_many :groups, through: :memberships, dependent: :destroy
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-06 03:10

    After carefully examining the API docs, it turns out has_many and has_and_belongs_to_many ("HABTM") have a few options just for this case:

    • before_add
    • after_add
    • before_remove
    • after_remove

    class User < ActiveRecord::Base
      has_many :groups, :through => :memberships, :after_remove => :your_custom_method
    end
    

    Judging by how many responses I got, this must not be a very well documented/used feature.

    Just noting it here for myself and others who may stumble like I did.

    0 讨论(0)
提交回复
热议问题