我的一个模型中有一个加密属性(我们称之为@model.encrypted_attribute)。在添加加密之前,我在我的模型中进行了以下验证:
validates_length_of :attribute, :minimum => 11, :maximum => 11, :allow_blank => true,
:message => "| Your attribute must be 11 digits long."
我还有一个方法可以运行before_save
,它会从属性中剔除所有非数字字符。但是,现在我不知道如何:
- 在加密和保存之前在属性上运行
gsub!(/\D/, '')
,或者在之后运行它并让 attr-encrypted 重新加密@model.attribute
值并将其写回数据库。我可以剥离字符,但不能重新加密/保存。 attribute
在保存之前对未加密的值运行验证。我曾尝试在 before_block 中添加以下代码,但随后出现不同的错误(undefined method '12345678' for #<Spree::Order:0x007fae02011cd0
):def format_attribute validates_length_of self.attribute.gsub(/\D/, ''), :minimum => 9, :maximum => 9, :allow_blank => true, :message => "| Your attribute should be 9 digits long." end
有谁知道我如何实现上述一项或两项,或者至少设置一个自定义方法在 attr_encrypted 执行其操作之前运行。
-------------编辑-------------
为搜索时遇到此问题的人留下两个以上但可以在验证加密中找到解决方案数据