This project is archived and is in readonly mode.

#6191 ✓resolved
Golly

HABTM association is being destroyed before the before_destory callbacks are executed

Reported by Golly | December 19th, 2010 @ 08:17 AM

Here is some example code.
Two models with a unique HABTM ass. on each other. One model has a before_destroy callback.

class AudioTag < ActiveRecord::Base
  has_and_belongs_to_many :tracks, :uniq => true

  before_destroy do |r|
    logger.info "[AudioTag] Before destroy"
  end
end

class Track < ActiveRecord::Base
  has_and_belongs_to_many :audio_tags, :uniq => true
end

Now the problem: from a unit test I run this: audio_tag.destroy
As you can see from the following logging, the association is destroyed before the callbacks are called.

  SQL (0.2ms)  SELECT COUNT(*) FROM `audio_tags`
  SQL (0.1ms)  SELECT COUNT(*) FROM `tracks`
  SQL (0.1ms)  select count(*) from audio_tags_tracks
  AudioTag Load (0.4ms)  SELECT `audio_tags`.* FROM `audio_tags` WHERE (`audio_tags`.`id` = 235380211) LIMIT 1
  Track Load (0.4ms)  SELECT * FROM `tracks` INNER JOIN `audio_tags_tracks` ON `tracks`.id = `audio_tags_tracks`.track_id WHERE (`audio_tags_tracks`.audio_tag_id = 235380211 )
  SQL (0.1ms)  SAVEPOINT active_record_1
  AREL (0.2ms)  DELETE FROM `audio_tags_tracks` WHERE `audio_tags_tracks`.`audio_tag_id` = 235380211 AND `audio_tags_tracks`.`track_id` IN (761148351)
  SQL (0.1ms)  RELEASE SAVEPOINT active_record_1
  SQL (0.1ms)  SAVEPOINT active_record_1
[AudioTag] Before destroy
  AREL (0.2ms)  DELETE FROM `audio_tags` WHERE (`audio_tags`.`id` = 235380211)
  SQL (0.1ms)  RELEASE SAVEPOINT active_record_1
  SQL (0.2ms)  SELECT COUNT(*) FROM `audio_tags`
  SQL (0.1ms)  SELECT COUNT(*) FROM `tracks`
  SQL (18.4ms)  ROLLBACK

So to be extra clear, the two lines that matter here are:

  AREL (0.2ms)  DELETE FROM audio_tags_tracks WHERE audio_tags_tracks.audio_tag_id = 235380211 AND audio_tags_tracks.track_id IN (761148351)


[AudioTag] Before destroy

The before_destroy callbacks should be called before any modifications are made to the model.

Most likely related to #4386.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Attachments

Referenced by

Pages