LoginSignup
0
0

More than 3 years have passed since last update.

バリデーションについて

Last updated at Posted at 2020-05-13

バリデーションとはデータベースにデータを登録する際に一定の制約をかけることを言います

バリデーションを設ける際はモデルに記載します

hoge.rb
validates :カラム名, バリデーションの種類

以下にバリデーションの種類の一例を載せておきます。

種類

空のデータはダメ(マイグレーションファイルにも記載)

validates :カラム名1, presence: true
 def change
    create_table :hoges do |t|
      t.カラム型 :カラム名1, null: falsenull: false
      t.カラム型 :カラム名2
        


      t.timestamps
    end
  end

既にデータベース上に存在しているデータ(重複しているデータ)はダメ

validates :カラム名, uniqueness: true

数値のみのデータでなければダメ

validates :カラム名, numericality: true

値の大小や長さの指定

validates :カラム名, length: { minimum: ~}          ←  ~文字以上
validates :カラム名, length: { maximum: ~}          ←  ~文字以下
0
0
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
0