Stephen Canis
Stephen Canis

Reputation: 93

Validating Longitude/Latitude with Geocoder Gem

I'm using the Geocoder gem in rails to generate latitudes/longitudes from an address. I've implemented validations based on the following stack overflow question:

Validating with Geocoder Gem

Model

  class Location < ActiveRecord::Base
  attr_accessible :address1, 
                  :country, 
                  :latitude, 
                  :longitude, 
                  :name

  validates :latitude, :presence => {message: "Not a valid location on Google Maps, please check name address & country fields" }

  geocoded_by :address
  after_validation :geocode, :if => :address_changed?

  def address
  [name, address1, country].compact.join(' ')
    end

    def address_changed?
  attrs = %w(name address1 country)
  attrs.any?{|a| send "#{a}_changed?"}
    end
end

My issue is that when a user edits their valid address to an invalid address the geocoder gem doesn't update the longitude/latitude fields. Therefore the longitude/latitudes remain valid even though the address isn't.

I'm new to rails and tried to find a way to set the longitude/latitude fields to nil before running the geocoder but couldn't find a method that worked. For example I tried to add the following into my edit form:

<%= f.hidden_field :longitude, value: nil %>
<%= f.hidden_field :longitude, value: nil %>

Upvotes: 1

Views: 684

Answers (1)

Kevin Y
Kevin Y

Reputation: 143

Active Record provides a before_validation callback.

before_validation :set_coords_to_nil, :if => :address_changed?

private

def set_coords_to_nil
    self.latitude = nil
    self.longitude = nil
end

Upvotes: 2

Related Questions