0

I am using a has_many through association and having trouble getting the before_destroy call back to trigger. I am using a Relating class to relate models.

class Relating < ActiveRecord::Base
  belongs_to :relater, :polymorphic => true
  belongs_to :related, :polymorphic => true

  before_destroy :unset_reminders
end

For example, a user can add TvShows to a list of favorites, User.rb:

has_many :tv_shows, :through => :relateds, :source => :related, :source_type => 'TvShow'

The problem I am having, has to do with deleting this Relating record.

I can relate users and tv shows by:

user = User.find(1)
show = TvShow.find(1)
user.tv_shows << show

But when I want to remove this association, the before_destroy is not triggered by:

user.tv_shows.delete(show)

However, if I destroy the relating record manually, it does trigger the callback:

r = Relating.find(8012)
r.destroy

How can I get the before destroy to be triggered for this?

Thanks

Paul
  • 401
  • 5
  • 16

1 Answers1

1

The delete method does not trigger callbacks as mentioned in the docs here. Try destroy instead.

Update: I didn't realize you were trying to destroy the join record and not the show itself. I'm surprised delete works at all but perhaps that is a feature of has_many :through. How about:

user.relateds.where(tv_show_id: show.id).destroy
ryanb
  • 16,227
  • 5
  • 51
  • 46
  • I tried this also...what seemed to happen was, 1. the record was not removed from the relating model, 2. the TvShow was completely removed from tv_shows... – Paul Jun 26 '12 at 23:01
  • Yes, this does work...I'm not too stoked on doing it this way, I wish I could find a way to have the before_destroy be triggered when simply doing user.tv_shows.delete(show) I wonder why before_destroy doesn't work when doing this...Anyway, thanks Ryan! – Paul Jun 26 '12 at 23:25