简体   繁体   English

在 Rails 5.1 之后,attribute_changed 是如何变化的? 更改“验证”回调?

[英]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在 Rails 4.1 中,当我的 model 中的属性发生更改时,我曾经调用验证方法

  validate :my_attribute_is_valid, if: :my_attribute_changed?

With Rails 5.1 and above (I'm using 6), the attribute_changed?对于 Rails 5.1 及更高版本(我使用的是 6),attribute_changed? Has changed for before_ and after_ callbacks (to saved_change_to_attribute? And will_save_change_to_attribute?, respectively).已更改 before_ 和 after_ 回调(分别为 saved_change_to_attribute?和 will_save_change_to_attribute?)。 What is the proper way to change the method check for “validate”?更改“验证”方法检查的正确方法是什么?

The correct would be: will_save_change_to_attribute?正确的是: will_save_change_to_attribute?

Validations run before save callbacks, therefore, you won't be able to checked for saved_changes just yet.验证在save回调之前运行,因此,您还不能检查saved_changes Available callbacks . 可用的回调

And as stated in the docs for will_save_change_to_attribute?正如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?它可以作为 will_save_change_to_name 调用吗? instead of will_save_change_to_attribute?("name").而不是 will_save_change_to_attribute?("name")。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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