简体   繁体   中英

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

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

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").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM