概要
strict
詳細
ActiveRecordで、validation時にstrictを利用することで、
検証エラー時に例外(ActiveModel::StrictValidationFailed)を投げます。
また、自分で任意のエラーを指定することも可能です。
サンプル
テーブル定義
CREATE TABLE "articles" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text, "created_at" datetime, "updated_at" datetime );
Validation その1 例外クラス指定なし時
class Article < ActiveRecord::Base has_many :comments, dependent: :destroy validates :title, length: { is: 5 , strict: true} end
試行 その1 例外クラス指定なし時
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 = '5' => "5" [3] pry(main)> a.valid? ActiveModel::StrictValidationFailed: Title is the wrong length (should be 5 characters) from /home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activemodel-4.1.1/lib/active_model/errors.rb:296:in `add' [4] pry(main)> a.title = '12345' => "12345" [5] pry(main)> a.valid? => true
Validation その2 例外クラス指定あり時
class SomeUserDefineError < StandardError;end class Article < ActiveRecord::Base has_many :comments, dependent: :destroy validates :title, length: { is: 5 }, strict: SomeUserDefineError end
試行 その2 例外クラス指定あり時
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 = '5' => "5" [3] pry(main)> a.valid? SomeUserDefineError: Title is the wrong length (should be 5 characters) from /home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/activemodel-4.1.1/lib/active_model/errors.rb:296:in `add' [4] pry(main)> a.title = '12345' => "12345" [5] pry(main)> a.valid? => true