validates_numercality_of with allow_nil.

In the model I have:

validates :square_meters_public_land, :barrier_meters, :numericality
=> { :greater_than_or_equal_to => 0 }, :allow_nil => true

but if, in the field, on create, I don't insert a value I have the
error "field is not a number".

Depending on your Rails version.... try:

  validates :square_meters_public_land, :barrier_meters, :numericality
=> { :greater_than_or_equal_to => 0 }, :if => {|o|


  validates :square_meters_public_land, :barrier_meters, :numericality
=> { :greater_than_or_equal_to => 0 }, :if =>

Include the :allow_blank option if the fields are not required.
I generally think about this in terms of "specifying a validation always includes :required; if that's not what I want, I have to include :allow_blank".


I'm using rails 3.0.9, sorry but I don't undestand why I have to use
the if clause.
allow_nil => doens't work with validation_numericality_of?

I didn't say you "had to", I suggested you try it... did you? Did it work?...

I doubt it anyway, as I had copied your code without checking it, and
just added the "if" I'd copied from one of my models. I notice now
that you're not using "validates_numericality_of", you're using
"validates" and seem to be trying to check two values - can't say
that's an idiom I'm familiar with, but it may be valid (although I
can't see it in the docs:

What about:

validates_numericality_of :square_meters_public_land,
:greater_than_or_equal_to => 0, :allow_nil => true
validates_numericality_of :barrier_meters, :greater_than_or_equal_to
=> 0, :allow_nil => true

It's just the same.

Same problem, I don't know how to insert nil values for the two fields.

Curious. Okay, so lastly, try:

validates_numericality_of :square_meters_public_land,
:greater_than_or_equal_to => 0, :if => :square_meters_public_land
validates_numericality_of :barrier_meters, :greater_than_or_equal_to
=> 0, :if => :barrier_meters

That's ok, they are numeric fields I thought that allow_nil should be ok.

I would have expected :allow_nil to work, but apparently it's giving problems? FWIW, I always tend to think in terms of :allow_blank rather than :allow_nil. Perhaps an artifact of my years in Smalltalk?
If :allow_nil isn't working, as I gather from the posts that appeared before mine (after I posted, but long before mine showed up), have you tried :allow_blank? Does that work better, worse, or no different?


allow_blank works.