[英]Checking if attribute_changed? in ActiveModel::EachValidator
I have a class Person that has first_name, middle_name, last_name.我有一个 class 人,他有名字、中间名、姓氏。 I have a customed Each validator for these 3 attributes like so
我有一个自定义的 Each 验证器,用于这 3 个属性,就像这样
validates :first_name, :middle_name, :last_name, nameValidator: true
In this validator I want to check if any one of these 3 attributes changed and given a few more conditions I'll validate name.在此验证器中,我想检查这 3 个属性中的任何一个是否已更改,并在给定更多条件后验证名称。 For that I'm trying attribute_changed?
为此,我正在尝试 attribute_changed? but it doesn't work.
但它不起作用。
I've checked different methods from ActiveModel::Dirty and Activerecod::Dirty but nothing seems to work to check changes in each attribute.我已经检查了 ActiveModel::Dirty 和 Activerecod::Dirty 的不同方法,但似乎无法检查每个属性的更改。 What am I missing?
我错过了什么?
module Person
class nameValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless can_normalize?(record)
#Normalization code
end
def can_normalize?(record)
anything_new = record.new_record? || attribute_changed?
end
end
end
If you need to check that some attribute was changed, you need to call attribute_changed?
如果您需要检查某些属性是否已更改,您需要调用
attribute_changed?
method on the record and pass this attribute like this记录上的方法并像这样传递此属性
return unless record.new_record? || record.attribute_changed?(attribute)
Or may be use metaprogramming method like this或者可以使用这样的元编程方法
return unless record.new_record? || record.public_send("#{attribute}_changed?")
Some notes:一些注意事项:
In Ruby we usually use PascalCase for class names and snake_case for hash keys在 Ruby 中,我们通常对 class 名称使用 PascalCase,对 hash 密钥使用 snake_case
Validations are used for data validation, not for some normalization.验证用于数据验证,而不是用于某些规范化。 It is usually used to add validation errors
它通常用于添加验证错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.