# Ticket for Review #765: Add :primary\_key option to belongs\_to association

**URL:** <https://discuss.rubyonrails.org/t/ticket-for-review-765-add-primary-key-option-to-belongs-to-association/33349>\
**Category:** rubyonrails-core\
**Created:** [August 18, 2008, 10:27pm UTC](https://discuss.rubyonrails.org/t/ticket-for-review-765-add-primary-key-option-to-belongs-to-association/33349 "2008-08-18T22:27:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Philip\_Hallstrom](https://avatars.discourse-cdn.com/v4/letter/p/bbe5ce/32.png) [@Philip\_Hallstrom](https://discuss.rubyonrails.org/u/Philip_Hallstrom)\
**Post date:** [August 18, 2008, 10:27pm UTC](https://discuss.rubyonrails.org/t/ticket-for-review-765-add-primary-key-option-to-belongs-to-association/33349/1 "2008-08-18T22:27:12Z")

</div>

Hi -

Several weeks ago ticket #292 added the ability to specify the primary  
key in a has\_many relationship and use that field instead of the  
primary key.

&nbsp;&nbsp;[http://rails.lighthouseapp.com/projects/8994/tickets/292-add-has\_many-primary\_key-option](http://rails.lighthouseapp.com/projects/8994/tickets/292-add-has_many-primary_key-option)

This doesn't exist for the belongs\_to side of that relationship.  
Ticket 765 (hopefully) fixes this.

&nbsp;&nbsp;[http://rails.lighthouseapp.com/projects/8994/tickets/765-primary\_key-option-for-belongs\_to#ticket-765-2](http://rails.lighthouseapp.com/projects/8994/tickets/765-primary_key-option-for-belongs_to#ticket-765-2)

With this patch applied one can now do this:

..... schema ......

&nbsp;&nbsp;&nbsp;&nbsp;create\_table :states do |t| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.string :abbr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.string :name &nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;create\_table :cities do |t| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.string :state\_abbr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.string :name &nbsp;&nbsp;&nbsp;&nbsp;end

..... models ......

class City \< ActiveRecord::Base &nbsp;&nbsp;belongs\_to :state, :primary\_key =\> :abbr, :foreign\_key =\> :state\_abbr end

class State \< ActiveRecord::Base &nbsp;&nbsp;has\_many :cities, :primary\_key =\> :abbr, :foreign\_key =\> :state\_abbr end

And assuming the tables are populated with the data you'd expect, you  
can use the association as normal.

\>\> wa = State.find(1) =\> #\<State id: 1, abbr: "WA", name: "Washington"\> =\> #\<City id: 1, state\_abbr: "WA", name: "Olympia"\> \>\> wa.cities.first.state =\> #\<State id: 1, abbr: "WA", name: "Washington"\>

Thanks for taking a look!

-philip
