I'm trying to use the geocoder gem to apply latitude and longitude coordinates to to my CoffeeShops model, but I can't get the geocoder to return the coordinates.

When I attempt to save a new instance of the class with an address, it saves successfully to the database, but the geocoding information for both longitude and latitude is 'nil'.

I've tried bundle installing. I've tried adding a timeout in geocoder.rb initializer I've tried adding and removing address validation (presence: true) in the model

My coffee shop model:

class CoffeeShop < ApplicationRecord
  belongs_to :user
  has_many :reviews
  has_one :feature_set
  has_one :wifi_speed, through: :feature_sets

  validates :name, :address, presence: true
  geocoded_by :address
  after_validation :geocode, if: :will_save_change_to_address?
end

My address migration file:

class AddAddressToCoffeeShops < ActiveRecord::Migration[5.2]
  def change
    add_column :coffee_shops, :address, :string
  end
end

My coordinates migration file:

class AddCoordiantesToCoffeeShops < ActiveRecord::Migration[5.2]
  def change
    add_column :coffee_shops, :latitude, :float
    add_column :coffee_shops, :longitude, :float
  end
end

My coffee shop schema:

create_table "coffee_shops", force: :cascade do |t|
    t.string "name"
    t.string "description"
    t.integer "rating"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.float "latitude"
    t.float "longitude"
    t.string "address"
    t.index ["user_id"], name: "index_coffee_shops_on_user_id"
  end

My geocoder initializer

Geocoder.configure(
  # Geocoding options
  # timeout: 3,                 # geocoding service timeout (secs)
  # lookup: :nominatim,         # name of geocoding service (symbol)
  # ip_lookup: :ipinfo_io,      # name of IP address geocoding service (symbol)
  # language: :en,              # ISO-639 language code
  # use_https: false,           # use HTTPS for lookup requests? (if supported)
  # http_proxy: nil,            # HTTP proxy server (user:[email protected]:port)
  # https_proxy: nil,           # HTTPS proxy server (user:[email protected]:port)
  # api_key: nil,               # API key for geocoding service
  # cache: nil,                 # cache object (must respond to #[], #[]=, and #del)
  # cache_prefix: 'geocoder:',  # prefix (string) to use for all cache keys

  # Exceptions that should not be rescued by default
  # (if you want to implement custom error handling);
  # supports SocketError and Timeout::Error
  # always_raise: [],

  # Calculation options
  units: :km,                 # :km for kilometers or :mi for miles
  # distances: :linear          # :spherical or :linear
)

0 Answers