1

I have an Address model which contains the fields: number, street, city, post_code.

I use a method called fulladdress to interpolate all the fields into one, which is then passed to geocoder which returns the Longitude and Latitude for the address.

Here is my Address model:

class Address < ActiveRecord::Base
    belongs_to :user

    def fulladdress
        "#{number} #{street}, #{city}, #{post_code}"
    end

    geocoded_by :fulladdress
    after_validation :geocode, :if => :number_changed?

end

At the moment, geocoder only updates the Long and Lat if number has changed. What I want is for geocoder to run if any of number, street, city, post_code change. What is the best practice way to do this?

mleko
  • 11,650
  • 6
  • 50
  • 71

1 Answers1

1

I've never worked with geocoder, but if you just want something to update if attributes change you could setup an after_save callback.

class Address < ActiveRecord::Base
    belongs_to :user

    def fulladdress
        "#{number} #{street}, #{city}, #{post_code}"
    end

    geocoded_by :fulladdress
    after_save :geocode

end

This should force it to update any time the address is updated, which should mean that at least one of the attributes has changed so no need to check if they are different.

tehfailsafe
  • 3,283
  • 3
  • 21
  • 27
  • I don't think this will work for geocode because geocode takes `:fulladdress` and calculates the latitude and longitude of the address and fills in the fields `:latitude` and `:longitude` on the address model. When the code is changed as above, the latitude and longitude fields remain empty on save. If I leave it as `after_validation :geocode` then it works however I am interested in how you would run geocode only when a field on the address object has changed. – blackfish64 Aug 18 '14 at 09:31
  • Since the address only has the fields that are in `:fulladdress` I don't understand the question. Every time the models saves, updates, or validates that means one of the fields in `:fulladdress` has changed. Unless the address model has more fields you aren't showing? – tehfailsafe Aug 18 '14 at 16:51