8

Rails 2.3.8. I have 3 models, User, Source, and Subscription.

User  attr_accessible   :source_ids
             has_many   :subscriptions
             has_many   :sources, :through => :subscriptions

Source       has_many   :subscriptions

Subscription belongs_to :user
             belongs_to :source

I have an interface that allows a User to edit their Subscriptions to a Source. It collects source_ids, and creates or deletes a Subscription based on the collection. The problem I am having is, quote:

"Automatic deletion of join models is direct, no destroy callbacks are triggered."

The Subscriptions are being deleted, not destroyed. I have a callback in the Subscription model that is not triggered:

before_destroy do |subscription|
  [Some irrelevant object not to be mentioned].destroy
end

My question is, how can I trigger this callback when a Subscription is automatically deleted due to the join model?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eric
  • 1,235
  • 2
  • 13
  • 26

2 Answers2

7

Replying to your reply in HMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered

Change this line:

 has_many :users, :through => :memberships

To this:

 has_many :users, :through => :memberships, :after_remove => :your_custom_method

And define protected your_custom_method in User model. This way when a user removes a Subscription to some Source, this method gets called.

Good luck!

Community
  • 1
  • 1
Swartz
  • 1,051
  • 2
  • 11
  • 23
  • Shouldn't `your_custom_method` be defined in the same file that `after_remove` is used? Not in the "User model" like you describe? – Joshua Pinter Oct 30 '18 at 05:29
2
@user.subscriptions.delete
has_many   :subscriptions, :dependent => :destroy    # <- setting this on the association  will destroy the related subscriptions
has_many   :subscriptions, :dependent => :delete_all # <- setting this on the association  will delete the related subscriptions

From the rdoc:

collection.delete(object, …)
Removes one or more objects from the collection by setting their foreign keys to NULL. Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :delete_all

inkdeep
  • 1,127
  • 9
  • 18