# Relationships on a non ID field

**URL:** <https://www.ruby-forum.com/t/relationships-on-a-non-id-field/173492>\
**Category:** Rails\
**Created:** [August 10, 2009, 2:35pm UTC](https://www.ruby-forum.com/t/relationships-on-a-non-id-field/173492 "2009-08-10T14:35:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pmckinstry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f6c823/32.png) [@pmckinstry](https://www.ruby-forum.com/u/pmckinstry)\
**Post date:** [August 10, 2009, 2:35pm UTC](https://www.ruby-forum.com/t/relationships-on-a-non-id-field/173492/1 "2009-08-10T14:35:25Z")

</div>

Hi Guys,

I am a total newbie to rails - so please go easy 🙂

So I have 2 models Country and City - the Country Model will have a  
‘name’ and a ‘code’ field (so a record would be

ID name code  
1 United Kingdom UK

Then my City table would look something like

ID country\_code city\_code name  
2 UK LON London

So I guess the question is can you use has\_many :city which would form  
the relationship based on the char code rather than a ID?

Regards

---

<div class="post-metadata">

**Author:** ![pmckinstry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f6c823/32.png) [@pmckinstry](https://www.ruby-forum.com/u/pmckinstry)\
**Post date:** [August 10, 2009, 2:52pm UTC](https://www.ruby-forum.com/t/relationships-on-a-non-id-field/173492/2 "2009-08-10T14:52:03Z")

</div>

On Aug 10, 1:35 pm, Pete M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Then my City table would look something like
> 
> ID country\_code city\_code name  
> 2 UK LON London
> 
> So I guess the question is can you use has\_many :city which would form  
> the relationship based on the char code rather than a ID?

has\_many does have a primary\_key option for this sort of thing. I  
would more commonly have a country\_id column on cities rather than a  
country\_code column

Fred

---

<div class="post-metadata">

**Author:** ![pmckinstry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f6c823/32.png) [@pmckinstry](https://www.ruby-forum.com/u/pmckinstry)\
**Post date:** [August 10, 2009, 2:54pm UTC](https://www.ruby-forum.com/t/relationships-on-a-non-id-field/173492/3 "2009-08-10T14:54:02Z")

</div>

Pete M. wrote:

> So I have 2 models Country and City - the Country Model will have a  
> ‘name’ and a ‘code’ field (so a record would be
> 
> ID name code  
> 1 United Kingdom UK
> 
> Then my City table would look something like
> 
> ID country\_code city\_code name  
> 2 UK LON London

Country  
ID name code  
1 United Kingdom UK

City  
ID country\_id city\_code name  
2 1 LON London

Country  
has\_many :cities

City  
belongs\_to :country
