This project is archived and is in readonly mode.

#5851 open
JackC

has_and_belong_to_many destroy with foreign key constraints broken

Reported by JackC | October 21st, 2010 @ 02:00 PM

Destroying a record with a has_and_belongs_to_many association fails if the join table has foreign key constraints. On Rails 2.3.X the association is cleared prior to deleting the record. On Rails 3.0, the association is cleared after the record is deleted.

Comments and changes to this ticket

  • JackC

    JackC October 21st, 2010 @ 02:01 PM

    • Tag changed from foreign key constraint destroy 3.0, has_and_belongs_to_many to foreign key, rails 3.0.0, constraint, destroy, has_and_belongs_to_many
  • Santiago Pastorino

    Santiago Pastorino February 2nd, 2011 @ 04:28 PM

    • State changed from “new” to “open”
    • Tag changed from foreign key, rails 3.0.0, constraint, destroy, has_and_belongs_to_many to foreign key, rails 300, constraint, destroy, has_and_belongs_to_many

    This issue has been automatically marked as stale because it has not been commented on for at least three months.

    The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.

    Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.

  • Santiago Pastorino

    Santiago Pastorino February 2nd, 2011 @ 04:28 PM

    • State changed from “open” to “stale”
  • Jeremy McNevin

    Jeremy McNevin March 18th, 2011 @ 03:56 PM

    • State changed from “stale” to “open”

    This problem seems to still exist as of 3.0.5. Currently, I need to define my own before_destroy callback to clear out HABTM associations, or a destroy operation will fail when the join table has foreign key constraints.

    [state:open]

  • JackC

    JackC April 9th, 2011 @ 03:17 PM

    A workaround for PostgreSQL users is to define the foreign keys as initially deferred. That will let Rails delete it in the wrong order without error.

  • JackC

    JackC April 13th, 2011 @ 09:48 PM

    Correction, deferred foreign keys don't work either. Rails is actually deleting the HABTM association after is commits the destroy transaction. This also could leave the database in an inconsistent state.

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>

Pages