Rails geocoder attribute
-
07-02-2021 - |
Pregunta
In the rails is it possible to make a function that everytime a particular attribute is changed, rails executes a function. In my case, everytime object.address (I have geocoded_by :address and after_validation :geocode) is changed, I want to do object.geocode. I am on rails 3
Solución
The best solution, I think would be to include ActiveModel::Dirty in your model, then you can check it in a callback
class MyModel < ActiveRecord::Base
def after_save
if address_changed? do
#some stuff..
end
end
end
Otros consejos
Just pass the field to check for dirtyness in you after_validation as in
after_validation :geocode, :if => :address_changed?
For me the most elegant solution is to use conditional validation based on whether or not the attribute to be geocoded_by (address) has changed. You can do something like this in the "after_validation" callback of the model you are geocoding, or place it in whatever Active Record callback suits your purpose:
after_validation :geocode, :if => lambda{ |obj| obj.address_changed?}