Search code examples
ruby-on-railsrails-geocoder

Geocoder looking for latitude and longitude fields but they don't exist


I'm using the Rails Geocoder Gem, Rails 4.2 and MySqL. I want to detect how many travels are compatible with some boxes.

Travels and boxes have these fields: departure_address, departure_lat, departure_long and arrival_address, arrival_lat, arrival_long.

When I want to check if a travel is compatible with a box I try with this query:

Travel.near([Box.last.departure_lat, Box.last.departure_long], 50)

I know it is considering only departure_address and not arrival_address but anyway it doesn't work because Geocoder tries to find a 'latitude' field in table 'travels' even if I called it 'dep_lat' and so on for longitude.

I want to solve this problem and then think to combine it with arrivals. Thanks!


Solution

  • You'll want to specify to GeoCoder that you aren't wanting to use their default lat and lon attribute names.

    To do this, add the following line to your model:

    geocoded_by :departure_address, :latitude  => :departure_lat, :longitude => :departure_lon # ActiveRecord
    

    You would do the same for your arrivals, but change the names of course.

    From the docs:

    You are not stuck with using the latitude and longitude database column names (with ActiveRecord). For example:

    geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord

    More information about this can be found in the Model Configuration section of the GeoCoder docs.