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.

Bad self referential HABTM associations should fail fast.

#1252

Self referential HABTM associations should not be allowed to be created unless the association_foreign_key has been manually assigned.

If this is not prevented, we end up with an join table which has only one column, which is referenced twice... causing odd and confusing results (which caused me a headache!).

This patch causes trying to do this to fail fast, saving on debug time.

Rough Example:


class Person < AR::Base
	habtm :friends, :join_table => :person_friend_pairings
end

alice = Person.create! :name => "Alice"  # id => 1
bob = Person.create! :name => "Bob"		 # id => 2
alice.friends << bob

alice.reload
alice.friends.to_a # SELECT * FROM person_friend_pairings where person_id = 2

Tagged as an enhancement, but could be a bug... feel free to change it.

Reported by Tom Lea · October 22nd, 2008 @ 11:36 PM

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

Activity

  1. Steven Soroka
    Steven Soroka

    isn't this because the habtm isn't set up properly? don't you need to identify the names of the foreign_key and association_foreign_key ?

    Sounds invalid to me.

    October 27th, 2008 @ 05:16 PM

  2. Tom Lea
    Tom Lea

    Indeed it is... but the fact that it pretends to work is the issue.

    The whole thing seems to work just fine, we were several unit tests in before it started behaving oddly. Anyone who tests less thoroughly than we do here could well be cough out.

    The patch makes it fail fast, not start magically guessing things.

    October 27th, 2008 @ 05:48 PM

  3. Steven Soroka
    Steven Soroka

    Ahh.

    code looks clean, fail early, fail often. +1

    October 27th, 2008 @ 08:20 PM

  4. Tom Lea
    Tom Lea

    New patch, error message was not as expected. Copied through relationship exception format by accident... oops.

    Also rebased against HEAD while I was at it.

    October 28th, 2008 @ 12:41 AM

  5. Repository
    Repository
    • State changed from new to resolved

    (from [c896d56c6e5520346c260477f7d7f8bf951e72cc]) Ensure self referential HABTM associations raise an exception if association_foreign_key is missing. [#1252 Bad self referential HABTM associations should fail fast. state:resolved]

    Signed-off-by: Pratik Naik pratiknaik@gmail.com http://github.com/rails/rails/co...

    March 6th, 2009 @ 06:28 PM