LoginSignup
0
2

More than 3 years have passed since last update.

Rails バリデーションとは

Posted at

RailsでDBに値を保存する際、無意味なデータや想定外のデータの登録を防ぐ「バリデーション」。備忘録として、書き方や例をまとめます。

バリデーションとは
先にも書きましたが、データを保存する前に、無効なデータでないことを検証する機能のこと。門番みたいなものです。
空のデータが保存されないようにしたり、数字以外は保存できないようにしたり、文字数に制限を設けたり……保存するデータに制限をかける時に使います。

基本的な書き方
Railsではモデルクラスに、validatesメソッドで指定します。

validates :カラム名(シンボルで指定),検証ルール(こちらもシンボルで指定)

これだけでは理解しづらいので、次から例を用いて書いていきます。
ユーザーモデルにname,age,email,genderのデータを追加していく例になります。

空データを登録できないようにする→presence

user.rb
class User < ApplicationRecord
  validates :name, presence: true
end

文字数の制限を設ける→length

user.rb
class User < ApplicationRecord
  validates :name, presence: true, length: { maximum: 50 }
end

ここでは名前の長さの上限を50文字にしました。下限や範囲の指定もできます。

#長さの下限を2文字に設定→minimum
validates :name, length: { minimum: 2 }
#長さの範囲を2-50文字→in .. 
validates :name, length: { in: 2..50 }
#長さを5文字に指定→is
validates :name, length: { is: 5 }

数値のみを許可する→numericality、空を許可するallow_blank
ageカラムは数字のみ、空でも構わない例です。

user.rb
class User < ApplicationRecord
  validates :name, presence: true, length: { maximum: 50 }
  validates :age, numericality: { only_integer: true }, allow_blank: true
end

numericalityは、デフォルトでは小数も許容してしまいます。ageカラムでは整数のみ許可したいので、 only_integerを。
また、numericalityは空を許可しないため、空を許可する場合はallow_blank: trueを追加します。(空を許可せず、数値のみを許可する場合はnumericalityのみ、 presence: trueは無くても良い。)

同一データは一つのみ許可する→uniqueness
emailカラムには同じデータを登録できないようにします。

user.rb
class User < ApplicationRecord
  validates :name, presence: true, length: { maximum: 50 }
  validates :age, numericality: { only_integer: true }, allow_blank: true
  validates :email, presence: true, uniqueness: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i}
end

ここではuniqueness: trueを用いました。format:では、文字列が条件に適しているかの検証を行います(ここでは割愛させていただきます)。

特定の値が含まれているか確認する→inclusion
genderカラムに、1~3(1:male, 2:female, 3:other)のいずれかの数字が保存されるとします。

user.rb
class User < ApplicationRecord
  validates :name, presence: true, length: { maximum: 50 }
  validates :age, numericality: { only_integer: true }, allow_blank: true
  validates :email, presence: true, uniqueness: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i}
  validates :gender, presence: true, inclusion: { in: 1..3 }
end

おわりに
ほんの一部ではありますが、validationについてまとめてみました。
まだまだ知らないことだらけですが、日々勉強していきます!

初心者ですので、間違っている点等あればご指摘いただけますと幸いです。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2