How to validate numericality and inclusion while still allowing attribute to be nil in some cases?

前端 未结 2 448
感动是毒
感动是毒 2021-01-17 09:44

In a Rails app I have several integer attributes on a model.

A user should be able to create a record and leave these attributes blank.

Or, if the user ente

相关标签:
2条回答
  • 2021-01-17 10:27

    You can add an :allow_nil => true to your validates_numericality_of.

    validates_numericality_of :a, :only_integer => true, :allow_nil => true, 
        :message => "can only be whole number."
    

    You can also use greater_than_or_equal_to and less_than_or_equal_to options if you just want to use one validation:

    validates_numericality_of :a, :only_integer => true, :allow_nil => true, 
        :greater_than_or_equal_to => 1,
        :less_than_or_equal_to => 999,
        :message => "can only be whole number between 1 and 999."
    
    0 讨论(0)
  • 2021-01-17 10:34

    should be simply:

    validates_numericality_of :a, :only_integer => true, :message => "can only be whole number.", :allow_nil => true
    

    same for the second validation

    0 讨论(0)
提交回复
热议问题