ActiveRecord のバリデーションを利用する - Ruby

ActiveRecord のバリデーション

require 'active_record'

ActiveRecord::Base.establish_connection( 
  adapter:  "mysql2", 
  host:     "localhost",
  username: "root", # ユーザー名
  password: "",  # MySQLのパスワード
  database: "sample",  # 接続するDB名
  encoding: "utf8",
  ssl_mode: "disabled"
)

class User < ActiveRecord::Base
  validates :mail, presence: true
  validates :password, presence: true
end

@user = User.new(mail: "", password: "")
@user.save

p @user.errors.full_messages
#=< ["Mail can't be blank", "Password can't be blank"]

バリデーションを引き起こし、問題ない場合のみデータベースに保存されるようにするには、以下のメソッドを使用します。

  • create
  • create!
  • save
  • save!
  • update
  • update!

バリデーションのエラーの状態を調べる

errors.details

バリデーションエラーがの詳細を調べるには「 errors.details 」を利用します。また属性をしていして取得することもできます。

@user.errors.details
#=> {:mail=>[{:error=>:blank}], :password=>[{:error=>:blank}]}

@user.errors.details[:mail]
#=> {:error=>:blank}

errors.attribute_names

バリデーションエラーになった属性を配列で取得することができます。

@user.errors.attribute_names
#=> [:mail, :password]

errors.clear

バリデーションのエラーメッセージをすべて削除します。

p @user.errors.full_messages
#=< ["Mail can't be blank", "Password can't be blank"]
@user.errors.clear
p @user.errors.full_messages
#=< []

errors.where

where の引数に「 :attr, :type, :option 」を指定してエラーメッセージ以外の情報を取得することができます。

引数の「 :attr 」以外は省略することができます。

class User < ActiveRecord::Base
  validates :mail, presence: true, length: { in: 4..8 }
  validates :password, presence: true
end

@user = User.new(mail: "", password: "")
@user.save

@user.errors.where(:mail).each do |error|
  p error
end

#<ActiveModel::Error attribute=mail, type=blank, options={}>
#<ActiveModel::Error attribute=mail, type=too_short, options={:count=>4}>

name 属性のエラーのタイプが「 too_short 」のみ取り出すには以下のようにします。

@user.errors.where(:mail, :too_short).each do |error|
  p error
end