Home > Net >  In post Rails 5.1, how does attribute_changed? chage for "validate" callbacks?
In post Rails 5.1, how does attribute_changed? chage for "validate" callbacks?

Time:12-22

In Rails 4.1, I used to invoke a validation method when an attribute is changed in my model

  validate :my_attribute_is_valid, if: :my_attribute_changed?

With Rails 5.1 and above (I’m using 6), the attribute_changed? Has changed for before_ and after_ callbacks (to saved_change_to_attribute? And will_save_change_to_attribute?, respectively). What is the proper way to change the method check for “validate”?

CodePudding user response:

The correct would be: will_save_change_to_attribute?

Validations run before save callbacks, therefore, you won't be able to checked for saved_changes just yet. Available callbacks.

And as stated in the docs for will_save_change_to_attribute?:

Will this attribute change the next time we save? This method is useful in validations and before callbacks to determine if the next call to save will change a particular attribute. It can be invoked as will_save_change_to_name? instead of will_save_change_to_attribute?("name").

  • Related