Railsのバリデーションの種類と使い方


プログラミングの勉強日記

2020年8月1日 Progate Lv.226

バリデーションとは

 不正なデータがデータベースに保存されないようにデータをチェックするシステムをバリデーションという。バリデーションに引っかかった場合(不正なデータの場合)にはデータベースに保存されない。

基本的な書き方

 モデルクラスにvalidatesメソッドを指定することで、バリデーションをかけることができる。(バリデーションはモデルで設定する。)このときに、validatesを用いてカルム名と内容を指定する。

model/ファイル名.rb
validates :カラム名(シンボルで指定),検証ルール(こちらもシンボルで指定)

バリデーションの種類

空ではい(空のデータを登録できないようにする)

 {presence: true}を用いることでそのカラムの値が存在するかどうかをチェックできる。

models/posts.rb
class Post < ApplicationRecord
  validates :content, {presence: true}
end

boolean属性が空でないこと

models/users.rb
class User < ApplicationRecord
  validates :birthplace, inclusion: { in: [true, false] }
end

チェックボックス

models/users.rb
class User < ApplicationRecord
  validates :gender, {acceptance: true}
end

文字数の指定

 lengthを用いて{maximum:数値}を指定することで最大文字数を{minimum:数値}で最小文字列を指定することができる。またinを使うことで範囲やその文字数のみのバリデーションをかけることもできる。

models/posts.rb
class Post < ApplicationRecord
  # 最大140文字(140文字以下)
  validates :content, {length : {maximum:140} }

  # 50文字以上
  validates :content, {length : {minimum:50} }

  # 1文字以上75文字以下
  validates :content, {length: {in: 1..75} }

  # 5文字のみ
  validates :content, {length: {is: 5} }
end

数値の指定

 数値のみの入力を許可するときには、numericalityを使う。

models/actorrb
class Actor < ApplicationRecord
    validates :height, {numericality: true}
end

 numericalityは様々なオプションがあるので、これらを用いることでより詳細なバリデーションをかけることができる。

オプション 概要
only_integer integerのみ
equal_to 指定された値と等しいか
greater_than_or_equal_to 指定された値以上
less_than_or_equal_to 指定された値以下
greater_than 指定された値よりも大きいか
less_than 指定された値よりも小さいか
odd trueに設定した場合、奇数か
even trueに設定した場合、偶数か
models/actor.rb
class Actor < ApplicationRecord
  # 50より大きく250より小さい
  validates :height, numericality: {greater_than: 50,less_than: 250}
end

任意で指定した値が含まれているかどうか

指定した値が含まれているか確認するときはinclusionを使う。

models/actor.rb
class Actor < ApplicationRecord
 validates :blood_type, inclusion: {in: ['A','B','O','AB']}
end

 指定した値が含まれていないか確認するときはexclusionを使う。

models/actor.rb
class Actor < ApplicationRecord
 validates :gender, exclusion: {in: ['male','female']}
end

値の重複

 値の重複がないかをチェックするための{uniqueness: true}というバリデーションもある。

models/posts.rb
class Post < ApplicationRecord
  validates :content, {uniqueness: true}
end

 

おまけ

複数のバリデーションの指定

 バリデーションの内容はハッシュになっているので、コンマで区切ることで複数指定できる。

models/posts.rb
class Post < ApplicationRecord
  validates :content, {presence: true, length : {maximum:140}}
end

自分で決めたエラーメッセージを表示する

 messageを追加することで自分で指定したエラーメッセージを表示させることもできる。

models/actor.rb
class Actor < ApplicationRecord
  validates :height, numericality: {greater_than: 50,less_than: 250, message: " : Please input 50~250"}
end