Search code examples
ruby-on-railsrubygeolocationrubygemsgeocode

Ruby Geocode: Make a model 'geocoded' when latitude and longitude already exist from other source?


In my app I have a Model and am retrieving the lat and lng values for each row from an external API unrelated to Geocode. At this time all I need Geocode for is the .nearbys method which lets me find other nearby models within the default radius (50 miles) or one that I specify.

Normally you "active" a model for Geocode by adding geocoded_by :attribute_name, where attribute_name will be used by Geocode when the object is saved to fetch the lat/long coordinates.

Right now I've simply added this to my model to get it to work:

geocoded_by :blargh, latitude: :lat, longitude: :lng

def blargh
end

This seems to work fine. I can open my console, instantiate a Model, and call model.nearbys. However, it seems a bit hacky and I'm wondering if there's a better way than just defining a fake method and passing that to geocoded_by. Many thanks in advance for any help!


Solution

  • Yesterday I had the same issue, even if this is an old question I share here my solution in case someone else needs it.

    You can directly include the Geocoder gem on your model requiring the file and defining the geocoder options (these in my case are simple the names of latitude and longitude on my db columns).

    Since I'm working with an ActiveRecord Model I needed to:

    require "geocoder/stores/active_record"
    
    class User < ActiveRecord::Base
      include Geocoder::Store::ActiveRecord
    
      def self.geocoder_options
        { latitude: 'latitude', longitude: 'longitude' }
      end
    
    end
    

    I think this is cleaner solution than having a fake address method.