pixeltrix/sortifiable — Issue #5: Weird problem with join model and dependent: :destroy
Author: masterkain
Created: 2012-02-14 02:22:09+00:00
State: open

Hi,
I'm using sortifiable on Rails 3.2.1.

My model setup is like this:

class MediaFile < ActiveRecord::Base
has_many :playlist_media_files, dependent: :destroy
has_many :playlists, through: :playlist_media_files

# playlist_id, media_file_id, position
class PlaylistMediaFile < ActiveRecord::Base
# WARNING: this will not delete the join model record in case the media gets destroyed
# and position is filled, but instead tries only to decrement the join model position.
# As result *_destroy callbacks for this model never runs, record will persist and playlists.updated_at does not get touched, not the counter decremented (see belongs_to declaration below)
acts_as_list scope: :playlist_id

belongs_to :playlist, touch: true, counter_cache: true
belongs_to :media_file

`playlist_media_files` has a column `position`.

When I try to `destroy` a `MediaFile` instance, the `dependent: :destroy` should wipe also the related `PlaylistMediaFile`, however if `position` *is not blank* `acts_as_list`'s `before_destroy` kicks in, *but* the `PlaylistMediaFile` instance won't continue its way to get destroyed, instead I see this:

(8.2ms) SELECT id FROM `playlist_media_files` WHERE `playlist_media_files`.`playlist_id` = 7 AND (`position` IS NOT NULL) ORDER BY position FOR UPDATE
SQL (0.4ms) UPDATE `playlist_media_files` SET `position` = `position` - 1 WHERE `playlist_media_files`.`playlist_id` = 7 AND (`position` IS NOT NULL) AND (`position` > 2292) ORDER BY position
# should delete the playlist_media_files record here, but it's not happening
SQL (0.4ms) DELETE FROM `media_files` WHERE `media_files`.`type` IN ('AudioFile') AND `media_files`.`id` = 594341