0

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

3 Answers 3

3

Just pass the field to check for dirtiness in your after_validation as in

after_validation :geocode, :if => :address_changed?
Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to check if 1 of 2 attributes have changed?
Simply make the symbol point to a method where you do the checking
0

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

see ActiveModel::Dirty

Comments

0

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?}

1 Comment

What if I want to check if 1 of 2 attributes have changed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.