如何将 validates_numericality_of 与小数字段一起使用?
我有一个表,其中有一列(剂量)定义为小数。当用户填写此列的表单字段时,我想确保他们输入有效的数字。我想使用 validates_numericality_of :dose ,但这不起作用。如果用户输入非数字值(例如“马”),则值 0 将保存到数据库中并且验证通过。我希望提出错误。
有没有办法在对象生命周期的早期捕获它?活动记录在什么时候将字符串转换为 0?
I have a table with a column (dose) that is defined as a decimal. When the user fills out the form field for this column I want to make sure they enter a valid number. I want to use validates_numericality_of :dose
but this doesn't work. If the user enters a non-numeric value (e.g. 'horse') a value of 0 is saved to the database and the validation is passed. I would prefer an error was raised.
Is there a way of catching this earlier in the object lifecycle? At what point is active record converting the string to a 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的期望是您有另一个插件或挂钩或其他阻碍并在验证之前更改值的东西。
为了更深入地了解情况,请向模型添加 before_validation 挂钩并引发 self.inspect 以在验证触发之前查看对象的外观。尝试使用 :dose 属性中的文本保存实例并查看它的外观。
My expectation would be that you have another plugin or hook or something that's getting in the way and changing the value before validation.
To maybe get some more insight as to what the situation is, add a before_validation hook to the model and raise self.inspect to see what the object looks like right before the validations fire. Try to save an instance with text in the :dose attribute and see what it looks like.