Search code examples
ruby-on-railsgoogle-mapsrails-geocodergeocoder

Any ideas how to setup geocoder with rails 5?


I am trying to get latitude and longitude from address but when I run rails db:seed latitude and longitude stay blank and the rest of the fields will be seeded

here is my model

    attr_accessor :lat, :lng
    geocoded_by :address, :latitude  => :lat, :longitude => :lng
    after_save :geocode, if: ->(building){ building.address.present? }

and I have gem 'geocoder' in GemFile

    My Rails version 5.0.6
    and ruby version 2.4.1

Note: I need to use only 'geocoder' gem That's all I have, thanks in advance


Solution

  • after_save means geocoding is done after the record is saved to the database and therefore the geocoding information itself is not saved into the database.

    Furthermore attr_accessor :lat, :lng overrides the getter and setter methods provided by Rails for the lat and lng database columns.

    Just change your code to:

    # remove this line: attr_accessor :lat, :lng
    geocoded_by :address, :latitude  => :lat, :longitude => :lng
    before_save :geocode, if: ->(building){ building.address.present? }