Previous related post: Rails – Find Location using Geocoder
Implementation of Geocoder on Model is simple and straight forward. What we need is just adding two more columns on the Model table for storing the coordinates(Latitude & Longitude) and one column for storing the address.
1. Add latitude, longitude and address to the User model
- rails generate migration AddLatitudeAndLongitudeAndAddressToUser latitude:float longitude:float address:string
2. Run the migration
- rake db:migrate
3. Add the following lines in app/model/user.rb
geocoded_by :address after_validation :geocode
4. Try how Geocoder works in Rails Console
# Get the first user user = User.first # Set the user address field user.address = "Hong Kong" # Generate the user latitude and longitude user.geocode # Check the user latitude and longitude user.latitude.to_s + " " + user.longitude.to_s
Here is an example which i changed the user address from Hong Kong to Taiwan. Notice that the latitude and longitude are changed also.
Done =)
Reference: GitHub – alexreisner / geocoder