Tbpgr Blog

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

Ruby on Rails | Validation | ActiveModel::EachValidator

概要

ActiveModel::EachValidator

詳細

ActiveRecord で、validation時に 再利用しやすく、Railsの組み込みのValidatorと同じように
呼び出せる Validator を作りたい場合、 ActiveModel::EachValidator を継承して 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::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A(hoge|hige|hage)\z/i
      record.errors[attribute] << "Title must be hoge, hige or hage."
    end
  end
end

class Article < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  validates :title, hoge_hige_hage: true
  validates :text, hoge_hige_hage: 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 = 'hege'
=> "hege"
[3] pry(main)> a.text = 'huge'
=> "huge"
[4] pry(main)> a.valid?
=> false
[5] pry(main)> a.errors.messages
=> {:title=>["Title must be hoge, hige or hage."],
 :text=>["Title must be hoge, hige or hage."]}
[6] pry(main)> a.title = 'hoge'
=> "hoge"
[7] pry(main)> a.text = 'hige'
=> "hige"
[8] pry(main)> a.valid?
=> true