Tbpgr Blog

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

Ruby on Rails | Validation | allow_nil

概要

allow_nil

詳細

ActiveRecordで、validation時にallow_nilを利用することで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_nil: true
end
試行

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

[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.errors.messages
=> {}