Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | Validation | allow_blank

概要

allow_blank

詳細

ActiveRecordで、validation時にallow_blankを利用することで nil, 空文字 を許容します。

サンプル

テーブル定義
CREATE TABLE "articles" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
  "title" varchar(255), 
  "text" text, 
  "created_at" datetime, 
  "updated_at" datetime
);
Validation
class Article < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  validates :title, length: { is: 5 }, allow_blank: true
end
試行

rails console(pry)で試行します。

Loading development environment (Rails 4.1.1)
[1] pry(main)> a = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[2] pry(main)> a.title = 6
=> 6
[3] pry(main)> a.valid?
=> false
[4] pry(main)> a.errors.messages
=> {:title=>["is the wrong length (should be 5 characters)"]}
[5] pry(main)> a.title = nil
=> nil
[6] pry(main)> a.valid?
=> true
[7] pry(main)> a.title = ''
=> ""
[8] pry(main)> a.valid?
=> true
[9] pry(main)> a.title = '    '
=> "    "
[10] pry(main)> a.valid?
=> true
[11] pry(main)> a.title = '12345'
=> "12345"
[12] pry(main)> a.valid?
=> true