Mongoid:ActiveModel数字验证,allow

编程入门 行业动态 更新时间:2024-10-27 07:31:50
本文介绍了Mongoid:ActiveModel数字验证,allow_nil不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经定义了一个 Mongoid模型,其中有一个Integer字段,我可以像这样验证数值

I've defined a Mongoid model with an Integer field for which i validate numericality like this

# source.rb class Source field :code, type: Integer validates_numericality_of :code, allow_nil: true

allow_nil的目的是验证存在的&字段.忽略零值.

The purpose of allow_nil is to validate fields which are present & ignore nil values.

但是在这里,allow_nil完全绕过了数值检查

But here, allow_nil completely bypasses the numericality check

object = Source.new object.code = "ABC" object.valid? => true object => #<Source _id: 50d00b2d81ee9eae46000001, _type: nil, code: 0>

在activerecord中,它可以正常工作

In activerecord, this works correctly

object = Source.new object.code = "ABC" object.valid? => false object => #<Source id: nil, code: 0, created_at: nil, updated_at: nil> object.save (0.1ms) begin transaction (0.1ms) rollback transaction => false

推荐答案

在使用#valid时,Mongoid的行为与Active Record略有不同?在已经存在的数据上. Active Record的#valid吗?将运行所有验证,而Mongoid的#valid?将仅在数据已更改为优化的字段上运行验证. -请参阅mongoid验证

Mongoid behaves slightly different to Active Record when using #valid? on already persisted data. Active Record's #valid? will run all validations whereas Mongoid's #valid? will only run validations on fields where data has changed as an optimization. - see mongoid validation

所以这可能是您的问题.

so this could be your problem.

您可以尝试

validates_numericality_of :code, :allow_nil => true

validates :code, :numericality => true ,:allow_nil => true

更多推荐

Mongoid:ActiveModel数字验证,allow

本文发布于:2023-11-22 19:04:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Mongoid   ActiveModel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!