melancholyfleur
melancholyfleur

Reputation: 105

Postgresql error when reverse geocoding in Ruby on Rails

I am having an issue trying to do a bulk reverse geocode using the geocoder rails gem: https://github.com/alexreisner/geocoder

I have the following models:

class School < ActiveRecord::Base
  reverse_geocoded_by :latitude, :longitude

  has_one :address
end

and

class Address < ActiveRecord::Base
  belongs_to :school
end

And the following migrations:

class CreateSchools < ActiveRecord::Migration
  def change
    create_table :schools do |t|
      t.string :name
      t.integer :address_id

      t.timestamps null: false
    end
  end
end

and

class CreateAddresses < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      t.string :line_1
      t.string :line_2
      t.string :line_3
      t.string :city
      t.string :region
      t.string :country
      t.string :code

      t.timestamps null: false
    end
  end
end

and when I run the following line: rake geocode:all CLASS=School REVERSE=true SLEEP=0.5

I get this error:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column schools.address does not exist
LINE 1: SELECT  "schools".* FROM "schools" WHERE (schools.address IS...
                                                  ^
: SELECT  "schools".* FROM "schools" WHERE (schools.address IS NULL)  ORDER BY "schools"."id" ASC LIMIT 1000

I know the readme says this:

"For geocoding your model must provide a method that returns an address. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: city, state, and country)."

I took that to mean I needed either a method on the School model or the attribute on the school table and I opted for the latter but I'm not sure what I'm missing.

Thanks!

Upvotes: 0

Views: 212

Answers (1)

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24591

The problem is that the reverse-geocoding rake task starts by loading all the records with no address column yet. It uses this scope:

scope :not_reverse_geocoded, lambda {
  where("#{table_name}.#{geocoder_options[:fetched_address]} IS NULL")
}

The problem is you don't have any column on schools you could use. Instead, you should move the reverse_geocoded_by declaration to the Address class. You will also need to either add an addresses.address column or do something like this:

reverse_geocoded_by :latitude, :longitude, fetched_address: :line_1

Also you don't seem to have columns for latitude and longitude. And of course those should be on Address too, not School. After all, if a school can have several addresses, which one is its lonlat?

Upvotes: 1

Related Questions