# Nested Attributes For HABTM - Deleting The Right Record

**URL:** <https://www.ruby-forum.com/t/nested-attributes-for-habtm-deleting-the-right-record/177841>\
**Category:** Rails\
**Created:** [October 25, 2009, 6:10am UTC](https://www.ruby-forum.com/t/nested-attributes-for-habtm-deleting-the-right-record/177841 "2009-10-25T06:10:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![MaggotChild](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/7ea924/32.png) [@MaggotChild](https://www.ruby-forum.com/u/MaggotChild)\
**Post date:** [October 25, 2009, 6:10am UTC](https://www.ruby-forum.com/t/nested-attributes-for-habtm-deleting-the-right-record/177841/1 "2009-10-25T06:10:52Z")

</div>

In a many-to-many relationship, defined via has\_and\_belongs\_to\_many,  
accepts\_nested\_attributes\_for deletes the wrong record(s) when  
marked\_for\_destruction? == true.

For example:

class Ho \< AR  
has\_and\_belongs\_to\_many :strolls, :join\_table =\> :ho\_strolls  
accepts\_nested\_attributes\_for :strolls, :allow\_destroy =\> true  
end

class Stroll \< AR  
has\_and\_belongs\_to\_many :hos, :join\_table =\> :ho\_strolls  
end

attribs = {“1”=\>{“\_delete”=\>“1”, :id=\>“123”}}

h=Ho.first  
h.strolls\_attributes = attribs  
h.save!

This will delete Stroll with an id of 123 from the join table and the  
strolls table.  
This is wrong. It should only be deleted from the ho\_strolls table.  
Though I believe there is a fix (or a debate still, maybe) on the way:  
[https://rails.lighthouseapp.com/projects/8994/tickets/2251-associationcollectiondestroy-should-only-delete-join-table-records](https://rails.lighthouseapp.com/projects/8994/tickets/2251-associationcollectiondestroy-should-only-delete-join-table-records)

At any rate, I have the following work around. It assumes that I’ll  
never delete a stroll from the strolls tables via a hoe. What do you  
think?

class Ho \< AR  
has\_and\_belongs\_to\_many :strolls, :join\_table =\> :ho\_strolls  
accepts\_nested\_attributes\_for :strolls, :allow\_destroy =\> true

def before\_save  
remove\_marked\_strolls  
end

def remove\_marked\_strolls  
marked = strolls.select { |stroll|  
stroll.marked\_for\_destruction? }  
marked.each { |stroll| stroll.delete(stroll) } #delete from join  
table only  
end  
end

I though about doing:

class Stroll \< AR  
…  
def unmark\_for\_deletion; @marked\_for\_deletion = false; end  
end

And then unmarking in remove\_marked\_strolls, though this seems  
superfluous since the records are remove from the collection the proxy  
will never get to check for this condition and delete them from  
strolls.
