How to integrate zipcode data into your Rails App

01 Jun 2006

Earlier I posted a list of all US zipcodes by city and state. I needed it for one of my sites and now I’m finding it handy for another. Instead of having people fill City, State, and Zip individually (with a high probability that the data won’t be standardized enough to do comparisons between records), you can simply accept a zip code from them and populate the rest yourself.

I create a Zip model that has the following three fields: code, city, state. I import the data into it like so (dependant on mysql):

    class CreateZips < ActiveRecord::Migration
      def self.up
        create_table :zips do |t|
          t.column  :city,      :string
          t.column  :state,     :string
        # load the zipcodes from a csv file
        execute "load data infile '#{RAILS_ROOT}/db/migrate/zips.csv' into table zips fields terminated by ',' lines terminated by '\n'"

      def self.down
        drop_table :zips

And I make sure my zips.csv file can be found in the ./db/migrate folder.

To associate this model with others, just add a belongs_to :zip and make sure that you’ve got a zip_id in the table schema. If you use the above migration the zipcode will be set as the table id and you can manually set zip_id to whatever zip code you want - handy for writing fixtures!

Now in my forms I only need to have a 5-char field that asks for a zipcode and (using lovely, lovely AJAX) displays the corresponding city and state automatically.

  • ricsrock said: I'd be interested to know exactly how you implement the ajax to populate the city & state from the zipcode.

Please if you found this post helpful or have questions.