属性设置器可以类型转换之前的验证 [英] validation before attribute setters can type cast

查看:34
本文介绍了属性设置器可以类型转换之前的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它有一个名为 value 的属性,它是 big decimal 类型.在类定义中,我有 validates_numericality_of.

I have an object with an attribute called value which is of type big decimal. In the class definition i have validates_numericality_of.

但是如果我:

a.value = 'fire'

'fire' 最终在验证触发之前将类型转换为正确的类型,因此:

'fire' ends up getting typecast to the correct type before the validation fires so:

a.valid? => true

如何在类型转换之前触发验证?

How do get the validation to fire before the typecast?

谢谢

推荐答案

来自 ActiveRecord::基础文档:

有时您希望能够阅读原始属性数据,而无需列确定的类型转换运行其当然第一.这可以通过使用 _before_type_cast所有属性都有的访问器.例如,如果您的 Account 模型具有一个 balance 属性,你可以调用account.balance_before_type_castaccount.id_before_type_cast.

Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast.

这在以下方面特别有用验证情况,其中用户可能为整数提供字符串字段,并且您想要显示原始字符串返回错误信息.访问属性通常会将字符串类型转换为0,这不是您想要的.

This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn’t what you want.

这篇关于属性设置器可以类型转换之前的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆