Reputation: 1624
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
Upvotes: 0
Views: 390
Reputation: 1713
Just pass the field to check for dirtiness in your after_validation as in
after_validation :geocode, :if => :address_changed?
Upvotes: 3
Reputation: 131
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?}
Upvotes: 0
Reputation: 5370
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
Upvotes: 0