:allow_nil doesn't work like you'd think

Posted by admin, Thu Oct 19 03:02:22 UTC 2006

I spent way too much time last week figuring out why :validates_length_of was not working after I added the :allow_nil option to it. Basically I have some optional fields, but if the user chooses to fill in those optional fields, they need to fall within a specific range, like this:

:validates_length_of :some_field, :in => 6..20, allow_nil => true

If you put this into a model in your Rails application, you would expect that on a form submit, this would allow the user to not enter anything, or to fill in a string from 6 to 20 characters in length. Instead, when you do not enter a value, the validation throws a range error.

Personally, I’d call this a BUG. But someone out there thinks it should be an enhancement:

#3375 (blank form fields pass empty params causing AR validations with :allow_nil to fail) – Ruby on Rails – Trac

blank form fields pass empty params causing AR validations with :allow_nil to fail

So, what is the real problem here? You aren’t getting a nil back from the form when “Submit” is pressed. You get the empty string. And since ”” != nil …

I am disturbed that this so-called enhancement has been moldering for months without resolution. It’s not an enhancement, it is a BUG. Rails does NOT do the logical/expected thing here. Perhaps the solution to the bug is to implement an enhancement (like :allow_blank or :allow_empty), but AT A MINIMUM, someone needed to get in and document that :allow_nil does not work on form validations.

Meanwhile, you can work around this problem by implementing a before_validation method that assigns nil to any blank/empty strings from your form that require this kind of validation.

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.