DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Numeric Colums For Latitude / Longitude In Rails 1.2 Migrations
In Rails 1.1.6, "numeric" datatypes didn't work in migrations. This confused a lot of people who wanted to store geographic data (latitude and longitude) for use in Google Maps and the like. Floats worked, but their precision is limited -- you'll lose three or more decimal places of precision if you store the results of a typical geocoding call in a Float column. And don't even think about using strings to store your latitudes/longitudes.
Fortunately, the numeric datatype problem is fixed in Rails 1.2, and you can now have do this in your migrations:
class CreatePlaces < ActiveRecord::Migration
def self.up
create_table :places do |t|
t.column "lat", :decimal, :precision => 15, :scale => 10
t.column "lng", :decimal, :precision => 15, :scale => 10
end
end
def self.down
drop_table :places
end
end
FYI, if you're stuck on Rails 1.1.6, you can use this approach:
class CreatePlaces < ActiveRecord::Migration
def self.up
create_table :places do |t|
t.column :lat, :float
t.column :lng, :float
end
execute("ALTER TABLE places MODIFY lat numeric(15,10);")
execute("ALTER TABLE places MODIFY lng numeric(15,10);")
end
def self.down
drop_table :places
end
end
... but that's ugly, database-specific (works on MySQL), and not very DRY.





