Mongoid: ActiveModel Numericality Validation, allow_nil does not work

送分小仙女□ 提交于 2019-12-13 00:54:22

问题


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

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

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> 

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

回答1:


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.

you could try

validates_numericality_of :code, :allow_nil => true

and

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



来源:https://stackoverflow.com/questions/13927637/mongoid-activemodel-numericality-validation-allow-nil-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!