What's New in Edge Rails: Validations Now :allow_blank

Posted by ryan
at 7:40 AM on Wednesday, September 05, 2007



This is a tiny update, but one worth mentioning. The various activerecord validation methods now accept an :allow_blank option that will let validation pass if the value is nil or an empty string.

1
2
3
4
5
6
class Post < ActiveRecord::Base
  validates_length_of :meta, :maximum => 3, :allow_blank => true
end

p = Post.new(:meta => "")
p.valid?  #=> true

Hardly earth-shattering, but convenient and a nice compliment to :allow_nil.

tags: ruby, rubyonrails

Comments

Leave a response

  1. Alex EggOctober 05, 2007 @ 12:23 AM

    So in the above example the meta db column does not allow null values right? And can you do this?

    validates_presence_of :subject, :allow_blank => true

  2. PaulOctober 16, 2007 @ 11:36 AM

    By allowing blanks you are saying to the form to return an empty string for that fields which is translated as a nil value in ActiveRecord. So effectively,

    validates_presence_of :subject, :allow_blank => true

    is contradictory (invalid).

  3. PaulOctober 18, 2007 @ 09:37 AM

    Please ignore my previous post. :allow_blank will skip validation for any nil or empty string (including whitespace string).

    :allow_blank is equivalent with :allow_nil + empty

    Mea culpa!