Mongoid: ActiveModel Numericality Validation, allo

2019-08-07 04:21发布

问题:

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