# Through method problems with custom foreign\_keys

**URL:** <https://www.ruby-forum.com/t/through-method-problems-with-custom-foreign-keys/54944>\
**Category:** Rails\
**Created:** [March 15, 2006, 12:25pm UTC](https://www.ruby-forum.com/t/through-method-problems-with-custom-foreign-keys/54944 "2006-03-15T12:25:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![chris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/958977/32.png) [@chris](https://www.ruby-forum.com/u/chris)\
**Post date:** [March 15, 2006, 12:25pm UTC](https://www.ruby-forum.com/t/through-method-problems-with-custom-foreign-keys/54944/1 "2006-03-15T12:25:19Z")

</div>

A person has a many company\_branches and  
A company\_branch has many people.  
This join is represented using a “contacts” table.  
I am using a legacy schema so i am forced into using non-standard rails  
primary keys. I am using the new through relationship in rails 1.1.

p=Person.find(1)  
b=p.company\_branches # gives this error:

ActiveRecord::StatementInvalid: OCIError: ORA-00904:  
“CONTACTS”.“COMPANY\_BRANCH\_  
ID”: invalid identifier: SELECT company\_branches.\* FROM contacts,  
company\_branch  
es WHERE (company\_branches.branch\_id = contacts.company\_branch\_id AND  
contacts.p  
erson\_person\_id = 1)

Notice that “contacts.company\_branch\_id” does not exist, it should be  
“contacts.com\_branch\_id”

Here are the models:

class Person \< ActiveRecord::Base  
set\_primary\_key “person\_id”

has\_many :contacts,  
:foreign\_key=\>“person\_person\_id”,  
:class\_name=\>“Contact”

has\_many :company\_branches,  
:through=\>:contacts,  
:foreign\_key=\>“com\_branch\_id”  
end

class CompanyBranch \< ActiveRecord::Base

set\_primary\_key “branch\_id”

belongs\_to :company,  
:foreign\_key=\>“cmpny\_company\_id”,  
:class\_name=\>“Company”

has\_many :contacts,  
:foreign\_key=\>“com\_branch\_id”,  
:class\_name=\>“Contact”  
end

class Contact \< ActiveRecord::Base  
set\_primary\_key “contact\_id”

belongs\_to :company\_branch,  
:foreign\_key=\>“com\_branch\_id”,  
:class\_name=\>“CompanyBranch”

belongs\_to :person,  
:foreign\_key=\>“person\_person\_id”,  
:class\_name=\>“Person”  
end

Any idea what is wrong? Any help would be greately appreciated!  
Thanks,  
Chris

---

<div class="post-metadata">

**Author:** ![chris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/958977/32.png) [@chris](https://www.ruby-forum.com/u/chris)\
**Post date:** [March 17, 2006, 11:15pm UTC](https://www.ruby-forum.com/t/through-method-problems-with-custom-foreign-keys/54944/2 "2006-03-17T23:15:58Z")

</div>

I believe I ran across the same problem when trying a self-referential  
has\_many :through relationship. I’ve submitted a patch at  
[http://dev.rubyonrails.org/ticket/4289](http://dev.rubyonrails.org/ticket/4289) that seems to fix it for me.  
You may want to give it a shot.
