This project is archived and is in readonly mode.

#3208 ✓duplicate
Tomash

belongs_to with :primary_key does not work with find's :include

Reported by Tomash | September 15th, 2009 @ 11:01 AM | in 2.3.9

Since 2.3.3 Rails supports both :foreign_key and :primary_key for belongs_to association.
Using both (or only :primary_key) works great for simple instance.owner.
However, when using Owned.find(..., :include => [:owner]) the owner gets joined using it's ID (model's own primary key) column instead of the :primary_key defined within Owned's (which is the expected behaviour) belongs_to :owner association.

Thus
owned.owner yields different results based on whether owned was pulled using Owned.find(id, :include => [:owner]) or Owned.find(id) (and of course .owner gets pulled when owned.owner gets called in the view).

It was pretty hard to stumble upon this error, as one needs to have some overlapping values in both columns. In our case it was
regions table has column "zip" (5-digit numbers)
users table has column "postal_code", User belongs_to(:region, :foreign_key => :postal_code, :primary_key => :zip)
It turned out that when using @user=User.find(id, :include => [:region]) the region was joined using regions.id instead of regions.zip:

SELECT "users".* FROM "users" LEFT OUTER JOIN "regions" ON "regions".id = "users".postal_code WHERE ("users"."id" = 1))

Comments and changes to this ticket

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