Monday, March 26, 2007

AJAX state_select

After downloading the state_select plugin for rails.
I put in a little extra work to make the state select AJAX updated.
The address form looks like:

<%= state_select 'address', 'state', country='US' %>

...
<%= country_select 'address', 'country' %>
<%= observe_field :address_country, :frequency=>0.5,
:update=>"state_select",
:url=> {:action=>'state_select', :only_path=>false},
with=>"'country=' + encodeURIComponent(value)" %>

Where the AJAX calls into a partial form:

<% if params[:country] == "United States" %>
<%= state_select 'address', 'state', country='US' %>
<% elsif params[:country] == "India" %>
<%= state_select 'address', 'state', country='INDIA' %>
<% elsif params[:country] == "Canada" %>
<%= state_select 'address', 'state', country='CANADA' %>
<% elsif params[:country] == "Australia" %>
<%= state_select 'address', 'state', country='AUSTRALIA' %>
<% elsif params[:country] == "Spain" %>
<%= state_select 'address', 'state', country='SPAIN' %>
<% elsif params[:country] == "Uganda" %>
<%= state_select 'address', 'state', country='UGANDA' %>
<% elsif params[:country] == "France" %>
<%= state_select 'address', 'state', country='FRANCE' %>
<% elsif params[:country] == "Germany" %>
<%= state_select 'address', 'state', country='GERMAN' %>
<% else %>
<%= text_field 'address', 'state', :class=>"text" %>
<% end %>

I have posted to their blog to see if the state_select could be updated so there was no translation needed between the "country" from select_country and the "country" parameter passed into the state_select. It would be also nice to return a text field if there is no state list for the given country.
This would mean the partial code would just be:

<%= state_select 'address', 'state', params[:country].uppercase %>

Thursday, March 22, 2007

Importing zip codes

This entry will show you how to quickly import zip codes into your database. From there, they can be used with AJAX lookups or verification.

Step 1: Download the zips.txt into your RoR (rails) db directory or some other place.
http://www.census.gov/tiger/tms/gazetteer/zips.txt

Step 2: Generate the table in MySQL

CREATE TABLE zip_codes (
id INTEGER NOT NULL AUTO_INCREMENT
, zip CHAR(5)
, state CHAR(2)
, town VARCHAR(50)
, population INTEGER
, PRIMARY KEY (id)
);


Step 3: Generate the model

ruby script\generator scaffold zip_code


Step 4: Run this import code

require 'csv'
CSV.open("#{RAILS_ROOT}/db/zips.txt", "r") do |row|
zip = ZipCode.new
zip.zip = row[1]
zip.state = row[2]
zip.town = row[3]
zip.population = row[6]
zip.save!
end


You can then monitor the table size and wait for it to grow to 29k+.