Mongoid:ActiveModel数字验证,allow_nil不起作用 [英] Mongoid: ActiveModel Numericality Validation, allow_nil does not work

查看:74
本文介绍了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_nil不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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