Rails 3 check if attribute changed
Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:
@user.street1_changed? # => true/false
This is how I solved the problem of checking for changes in multiple attributes.
attrs = ["street1", "street2", "city", "state", "zipcode"]
if (@user.changed & attrs).any?
then do something....
end
The changed
method returns an array of the attributes changed for that object.
Both @user.changed
and attrs
are arrays so I can get the intersection (see ary & other ary
method). The result of the intersection is an array. By calling any?
on the array, I get true if there is at least one intersection.
Also very useful, the changed_attributes
method returns a hash of the attributes with their original values and the changes
returns a hash of the attributes with their original and new values (in an array).
You can check APIDock for which versions supported these methods.
http://apidock.com/rails/ActiveModel/Dirty