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.

Association IDs carry over to associated model

#81

I've had big problems with this bug in 2.0.2 & 2.0.3.

In Rails Edge (2.0.3) and 2.0.2, I'm having problems with has_many associations where there are colliding names for id fields. The #{model}_id of the associated record takes the #{model}_id value from the join table, not it's own value.

I have:

Emails

has_many contacts

Contact

has_one :user

has_one :contact, :class_name => 'User' (foreign_key: contact_id)

Join Table, contacts_emails

t.integer :email_id

t.integer :contact_id

Note that a column named "contact_id" is in two tables: contacts and contacts_emails.

If you call emails.contacts, you'll get an array of Contacts, obviously.

The bug is that the array that's returned of Contacts will have contact_id set to the contact_id that's in the joining contacts_emails row, not that's in the contacts row.

-----

Example

contacts_emails

------------------

email_id | contact_id

1 3

contacts

------------------

id | email_id | contact_id

3 1 2

users

------------------

id | first_name

2 User

If you do emails.contacts, one Contact will be returned (which is correct).

emails.contacts[0].contact_id will be 3, not 2 as it should be in the table above.

emails.contacts[0].reload.contact_id will correctly be 2.

This is caused because there is a collision on contact_id. If I change contact's contact_id to contact_user_id, it works perfectly.

Reported by Matthew Moore · May 1st, 2008 @ 05:21 PM

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

Activity

  1. josh
    josh
    • State changed from new to stale
    • Tag set to activerecord, associations, bug

    Closing this ticket as stale. If this is still an issue for you, feel free to reopen this ticket or create a new one with an updated description. Remember those unit tests too ;)

    July 17th, 2008 @ 12:57 AM