Why isn't it validated! ?? (unique: true edition)

No. I was really surprised. I'm currently implementing a flea market app on rails 5.2. : frowning2: Validation everyone will do it, right? Yeah I know. Everyone feels the same as Atai. : girl_tone2: I know Atai. First of all. It seems that validation should be written in both the model and the migration file, This time it's about the migration file, so it's a good idea to refer to other people's articles regarding the validation of the model.

1. The first thing I want you to see is this!

:writing_hand_tone1:

db/migrate/create_users.rb


class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :first_name,         null:false ,unique: true
      t.string :last_name,          null:false ,unique: true
}

Like this. Let's go!

2. Let's

:point_down_tone1:

console

 rails db:migrate

Then. :raised_hand:

db/migrate/schema.rb


 create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "first_name", null: false
    t.string "last_name", null: false
}

Zugoooooooooooooooooooooooooooooooooooooooooooooooooooo !!

:man_tone1: null: false is validated, but unique: true isn't! !! !! Why. .. .. Attai I haven't learned with such an error curriculum. Ah, it's already a painful Japan.

In such a case, this! !!

Let's go see mysql.

In short, the DB is not validated either.

It's a tough America! !! !! I'll look it up already. .. ..

3 ... a few minutes later ...

I found something like this.

Rails documentation

according to it. .. ..

 add_index :users, [:name], unique: true

Is it true! !! !! I'm new to you! e! ?? I'm new to you! !!

Don't you believe it? e? Don't you believe it? It's not that easy

db/migrate/schema.rb


 create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
  t.string "first_name", null: false
  t.string "last_name", null: false
  t.index ["first_name"], name: "index_users_on_first_name", unique: true
  t.index ["last_name"], name: "index_users_on_last_name", unique: true
}

No, it ’s real! !! !!

:clap_tone1: That's possible. I don't know if anyone has the same situation as me, but it will be helpful to you: frowning2 :! !! !!

see you.

Recommended Posts

Why isn't it validated! ?? (unique: true edition)
Reading Memo "Why make it object-oriented"
Why isn't it validated! ?? (unique: true edition)