我已经定义了一个 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: trueallow_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
发布评论