# Sorting Out My Countries

**URL:** <https://www.ruby-forum.com/t/sorting-out-my-countries/179613>\
**Category:** Rails\
**Created:** [November 30, 2009, 3:24pm UTC](https://www.ruby-forum.com/t/sorting-out-my-countries/179613 "2009-11-30T15:24:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bingobob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/e480ec/32.png) [@bingobob](https://www.ruby-forum.com/u/bingobob)\
**Post date:** [November 30, 2009, 3:24pm UTC](https://www.ruby-forum.com/t/sorting-out-my-countries/179613/1 "2009-11-30T15:24:18Z")

</div>

I’ve got a database structure which has this sort of thing.

A Resort is in a particular country.

Presently the country is stored in a field in the Resort model,  
Resort.country (a string).

I want to do this properly and have done the following

1. added a new field to resort called country\_id.
2. creating a countries table Country with just name:string
3. Load up a list of all unique countries into my Country model
4. Resort belongs\_to country
5. Country has\_many resorts
6. Somehow I now need to add the relevant country\_ids to each Resort by  
searching Resort.country and matching against Country.name

Anyone help me - is this on the right lines? and how do I do step 5 (got  
the rest I think).

---

<div class="post-metadata">

**Author:** ![bingobob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/e480ec/32.png) [@bingobob](https://www.ruby-forum.com/u/bingobob)\
**Post date:** [November 30, 2009, 10:59pm UTC](https://www.ruby-forum.com/t/sorting-out-my-countries/179613/2 "2009-11-30T22:59:27Z")

</div>

> Anyone help me - is this on the right lines? and how do I do step 5 (got  
> the rest I think).

Well, you _could_ approach it with a migration… it doesn’t have to be  
ALL table creation, structure modification, etc, etc.

UP:  
resorts = Resort.find(:all)  
resorts.each do |resort|  
if resort.country\_id.nil?  
country = Country.find\_by\_name(resort.country)  
if found == store the country id in resort country\_id  
if not found == add the name to countries, get the new ID and stick  
that in  
resort country\_id  
end  
end

DOWN:  
for each resort, clear the country\_id
