LoginSignup
1
1

More than 3 years have passed since last update.

バリデーションの書き方(Rails)

Last updated at Posted at 2021-03-25

バリデーションとは

バリデーションは、正しいデータだけをデータベースに保存するために制約をかける事です。
modelに書くことでデータベースに保存する前に受け取った情報を正しいのか判定させます。

空でないこと

validates :name, presence: true

空であること

validates :name, absence: true

一意性であること(重複していないこと)

validates :name, uniqueness: true

文字数制限

validates :name, length: { minimum: 2 }  # 2文字以上
validates :name, length: { maximum: 50 } # 50文字以下
validates :name, length: { in: 2..50 }   # 2文字以上50文字以下
validates :name, length: { is: 6 }       # 6文字のみ

Boolian型

validates :publish, inclusion: { in: [true, false] }

数値制限

validates :fee, numericality: { greater_than: 0 } 
validates :fee, numericality: { ess_than: 250 }
validates :fee, numericality: { greater_than: 0, less_than: 250 }
#greater_than: 0   0 < fee 0より大きく
#ess_than: 250   250 < fee 250より小さい

参考

Active Record バリデーション Railsガイド v.6.1

1
1
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
1
1