Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Ruby on Rails | Validation | validates_with

概要

validates_with

詳細

ActiveRecordで、validation時にvalidates_withを利用することで、
任意のValidatorでチェックを行うことができます。

サンプル

テーブル定義
CREATE TABLE "articles" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
  "title" varchar(255), 
  "text" text, 
  "created_at" datetime, 
  "updated_at" datetime
);
Validation
class HogeHigeHageValidator < ActiveModel::Validator
  def validate(record)
    unless record.title =~ /\A(hoge|hige|hage)\z/i
      record.errors[:base] << "Title must be hoge, hige or hage."
    end
  end
end

class Article < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  validates_with HogeHigeHageValidator
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 = 'not hoge'
=> "not hoge"
[3] pry(main)> a.valid?
=> false
[4] pry(main)> a.errors.messages
=> {:base=>["Title must be hoge, hige or hage."]}
[5] pry(main)> a.title = 'hoge'
=> "hoge"
[6] pry(main)> a.valid?
=> true
[7] pry(main)> a.title = 'HoGe'
=> "HoGe"
[8] pry(main)> a.valid?
=> true
[9] pry(main)> a.title = 'hige'
=> "hige"
[10] pry(main)> a.valid?
=> true
[11] pry(main)> a.title = 'hage'
=> "hage"
[12] pry(main)> a.valid?
=> true
[13] pry(main)> a.title = 'hogehige'
=> "hogehige"
[14] pry(main)> a.valid?
=> false
[15] pry(main)> a.errors.messages
=> {:base=>["Title must be hoge, hige or hage."]}