Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

polymorphic :dependent => :delete_all fails to delete rows with abstract_class instances

#6441

If I have a class hierarchy ContactIndex < Index, GuideIndex < Index, where Index is

  class Index < ActiveRecord::Base
    has_many :links, :as => :link_owner, :dependent => :delete_all
  end

and Link is

  class Link < ActiveRecord::Base
    belongs_to :link_owner, :polymorphic => true
  end

When I instantiate and save a GuideIndex, the links table gets a row with a link_owner_type of Index. When I subsequently delete the index, the links rows are orphaned:

  i = GuideIndex.new
  i << Link.new(:url => 'http://somewhere')
  i.save    # This creates links row with link_owner_type = 'Index'
  i.destroy # This tries to delete rows with link_owner_type = 'GuideIndex' and finds no rows

At present, my workaround is this:

  class Index < ActiveRecord::Base
    has_many :links, :as => :link_owner
    before_destroy :delete_links

  private
    def delete_links
      Link.delete_all ['links.link_owner_id = ? AND links.link_owner_type = ?', self.id, 'Index']
    end
  end

Reported by Russell Garner · February 16th, 2011 @ 11:03 AM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Russell Garner
    Russell Garner

    (oops - abstract_class is not involved here - the title should read STI. Sorry!)

    February 16th, 2011 @ 11:20 AM