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.

There was a problem

You must be a member of this account.

This project is archived and is in readonly mode.

Calling delete on a has_many :through association does not call destroy on the association object

#1843

Here is an example:


class GroupContentAssignment < ActiveRecord::Base
  belongs_to :group
  belongs_to :content, :counter_cache => true
  
  has_many :annotations, :dependent => :destroy
end

class Group < ActiveRecord::Base
  has_many :group_content_assignments, :dependent => :destroy
  has_many :assigned_contents, :through => :group_content_assignments
end

class Content < ActiveRecord::Base
  has_many :group_content_assignments, :dependent => :destroy
end

If I do the following...


group = Group.first
content = Content.first
group.assigned_contents << content

... an instance of GroupContentAssignment is created and saved and the counter_cache field on Content is incremented. But when removing...


group.assigned_contents.delete content

... no call to the destroy method of GroupContentAssignment is made and so destroy is not called for all its annotations and the counter_cache of the belonging Content is not decremented.

See also: #1196 counter_cache not decrementing on delete, http://railsforum.com/viewtopic....

Reported by Martin Andert · February 2nd, 2009 @ 11:03 AM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Martin Andert
    Martin Andert

    Forgot the Annotation model above:

    
    class Annotation < ActiveRecord::Base
      belongs_to :group_content_assignment
    end
    

    To make things clearer...

    
    group.assigned_contents.delete content
    

    ... deletes the association record in the db using SQL, but doesn't call destroy on its AR instance, so all annotations aren't destroyed (although declared with dependent => destroy).

    February 2nd, 2009 @ 11:15 AM

  2. Martin Andert
    Martin Andert

    Commit 47bdf3bf40ec17e1f8ca1c0e3d7f697d0c4cd1bf added a destroy method to AssociationCollection. Now I can call

    
    group.assigned_contents.destroy content
    

    instead of calling

    
    group.assigned_contents.delete content
    

    This should fix it.

    March 15th, 2009 @ 07:52 PM

  3. Eloy Duran
    Eloy Duran
    • State changed from new to resolved

    I'm closing this, since that's probably what you meant to say, even though you reported a problem with the current behaviour to #2146 AutosaveAssociation doesn't run removing association callbacks. As I commented on that ticket, please open a new ticket with for the specific problem for any further discussion.

    Thanks

    March 16th, 2009 @ 09:54 AM