Rails : Auto updating geo-coded object attributes

Lets say you are setting your model such that, user only needs to set / input their zipcode and whenever they modify the zipcode the application needs to re-calculate the address information like country, city, state, etc.

# in geo-codable model
geocoded_by :zip_code

after_validation :geocode, if: ->(obj){ obj.zip_code.present? && obj.zip_code_changed? }
after_validation :reverse_geocode, if: ->(obj){ obj.zip_code.present? && obj.zip_code_changed? }

reverse_geocoded_by :latitude, :longitude do |obj, results|
  if geo = results.first
    obj.state = geo.state
    obj.city = geo.city

In the setup above, zip_code field in the table is used to gather the geo-coordinates which will be stored in lat and long field. This is forward geo-coding.

And whenever zip_code changes, we need to recalculate the long, lat . Also we need to re-update the state and city information.

So, the code above does the stuff smoothly.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s