1

I've had an address table in my database for some time now, and recently have come across the Geocoder gem (sweet gem). Anyway, I've edited my model to include both the latitude and longitude columns, as well as specify what each record is supposed to be geocoded_by, so now I would like to simply geocode all of the addresses in the table now that currently have nil latitudes and longitudes.

I thought I had figured it out with the rails console, simply by running the command:

    Address.all.each{ |address| address.geocode }

This returns each entry with a filled in latitude and longitude column, however upon inspection of the individual elements afterwards - they still have nil latitudes and longitudes (i.e. the records are not actually being updated). I thought maybe address.geocode! would work, but that returned a NoMethodError.

This has got to be a simple one, but it seems I'm just inexperienced enough to not know what it is... aaaand with a little more tinkering I figured it out:

Solution

    Address.all.each{ |address| address.update_attributes(latitude: address.geocode[0], longitude: address.geocode[1]) }

2 Answers 2

6

Simply performing

    Address.all.each{ |address| address.geocode }

Does not actually change the records in the database.

Solution

Needed to use update_attributes:

    Address.all.each{ |address| address.update_attributes(latitude: address.geocode[0], longitude: address.geocode[1]) }

There may be quicker solutions out there embedded within Geocoder, but this was a quick solution to the problem, hope it helps others!

Sign up to request clarification or add additional context in comments.

Comments

0

Here's how I would do it:

geocode a single record:

address = Address.first
address.geocode
address.save

geocode all:

Address.all.each { |address| address.geocode && address.save }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.