[RUBY] Summary of basic migration knowledge rails db: rollback and column addition / deletion

Introduction

[Knowledge gained from this article] ・ About migration -Rails db: rollback execution procedure -Procedure for adding and deleting columns -Execution procedure of addition and deletion when column is reference type

【environment】 ・ MacOS Catalina ・ Rails 6.0.0 ・ Ruby 2.6.5

What is migration?

・ Table design drawings and specifications -Has an important role in creating tables in the database -Write column type, column name and option information in the migration file -You can create / change the table by reflecting the information.

Migration execution procedure

① Create a model (2) Describe the necessary information in the migration file (db / migrate / 2020 ~~~~ .rb) generated when creating the model.

db/migrate/20201014123456_create_address.rb


class CreateAddresses < ActiveRecord::Migration[6.0]
  def change
    create_table :addresses do |t|
    # t.Column type:Column name,option
      t.string :postal_code,    null: false
      t.string :city,           null: false
      t.string :address_line,   null: false
      t.string :phone_number,   null: false
      t.references :order,      null: false, foreing_key: true
      t.timestamps
    end
  end
end

③ Execute rails db: migrate in the terminal after confirming that you are in the directory of the application you are creating to reflect the columns of the described table.

% rails  db:migrate

④ Success if the terminal has the following description!

== 20XXXXXXXXXXXX CreateAddresses: migrating ======================================
-- create_table(:addresses)
   -> 0.0395s
== 20XXXXXXXXXXXX CreatePosts: migrated (0.0396s) =============================

Just in case, check if the information described in sequel pro is displayed.


I made a mistake in the table even though I migrated rails db: migrate!

"What should I do,,," There are times when you say, "I want to edit the migration!"

However, once it is executed, it cannot be executed again. The reason is that the design is recorded as a history so that you can check what changes you have made later.

If you want to change the column name due to a misspelling, you don't want to bother to leave the change in the history.

In that case, use the `rails db: rollback command`. (Since the reflected information can be returned, the change history will not remain.) Otherwise, ** create a migration file for adding / removing columns ** and make changes. (History remains because a new file is created and changed.)

I would like to explain these below.


rails db: rollback execution procedure ① ~ ⑥

① Check the status of the migration file with the `rails db: migrate: status command`

% rails db:migrate:status

-When executed, the migration history is displayed, and the status is displayed with status up and down. ・ Up means that it has been executed, and down means that it can be modified.

# rails db:migrate:status Execution result

database:app name_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20201001015223  Create orders
   up     20201001092756  Create addresses
   up     20201014023427  Add id to addresses
   up     20201014030100  Add id to orders

② Execute rails db: rollback to change up (executed) to down (modifiable)

% rails db:rollback

③ Execute rails db: migrate: status again to check the status of the migration file.

database:app name_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20201001015223  Create orders
   up     20201001092756  Create addresses
   up     20201014023427  Add id to addresses
  down    20201014030100  Add id to orders

④ If you can confirm that the status of the migration file you want to change is down, in this case modify the db / migrate / 2020101430100_ ~~ .rb file. ⑤ Execute `` `rails db: migrate``` to reflect the correction contents

% rails  db:migrate

⑥ Just in case, check if the information described in sequel pro is displayed.

【Supplementary information】

If you want to roll back any migration file and bring it down

rollback STEP=Numerical value(What is the number you want to return to from the bottom)Describe and execute like this


 * The bottom is 1.

```terminal
#If you want to roll back the second from the bottom
% rails db:rollback STEP=2

If you check the status, you can see that it is down from the bottom to the second

database:app name_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20201001015223  Create orders
   up     20201001092756  Create addresses
  down    20201014023427  Add id to addresses
  down    20201014030100  Add id to orders

After that, modify the migration file in the same way and execute `` `rails db: migrate```

Column addition / deletion execution procedure (Patterns 1 and 2)

First, as a prerequisite knowledge, write add_column to add a column and `` `remove_column``` to delete a column.

    #Add column
    add_column :users, :first_name, :string
    #Delete column
    remove_column :users, :last_name, :string

Pattern 1: How to write in order

① Execute `rail g migration file name` The file name is ```Add column name To. Table name to which it is added` `` (The file name may be arbitrary, but when Add ~ To ~ is viewed later, it is a fixed file name. Toward)

#When adding the name column to the Users table
% rails g migration AddNameToUsers

Contents of the generated file

db/migrate/20200000000000_add_names_to_users.rb


class AddNamesToUsers < ActiveRecord::Migration[6.0]
  def change 
  end
end

(2) Describe the information in the newly generated migration file.

db/migrate/20200000000000_add_names_to_users.rb


class AddNamesToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string
  end
end

③ Execute rails db: migrate

% rails  db:migrate

Pattern 2: How to write in a terminal

`rail g migration file name Column name to be added: Execute type`

#Describe the detailed information of the column to be added
% rails g migration AddNameToUsers first_name:string last_name:string

Contents of the generated file (Migration file is generated with the contents of the file described)

db/migrate/20200000000000_add_names_to_users.rb


class AddNamesToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string
  end
end

② Execute rails db: migrate

% rails  db:migrate

Addition / deletion of references type column Execution procedure

Situation: Add address_id as a foreign key to the Orders table

① Execute `rails g migration file name`

# address_When adding the id column to the Orders table
% rails g migration AddIdToOrders

② Write in the generated file

db/migrate/20201014000000_add_id_to_orders.rb


class AddIdToOrders < ActiveRecord::Migration[6.0]
  def change
    #add to
    add_reference :orders, :address, foreign_key: true
    #Delete
    remove_reference :orders, :address, foreign_key: true
  end
end

Additional points -It must be add_reference -Write foreign_key: true (only if necessary) Point of deletion -It must be remove_reference

③ Execute rails db: migrate

% rails  db:migrate

That's all for the explanation! !!

It's been longer than I imagined, but I hope you find this article useful. It's easy once you get used to it, so let's learn it so that development can proceed smoothly! Thank you for watching until the end.

reference

・ Https://qiita.com/kurawo___D/items/e3694f7a870a1cc4738e ・ Https://freesworder.net/rails-column-add-remove/ ・ Https://gist.github.com/seak0503/84bfa6b37a0a6961c334

Recommended Posts

Summary of basic migration knowledge rails db: rollback and column addition / deletion
Summary of basic knowledge of Rails acquired by progate
Basic knowledge of Ruby on Rails
Rails Addition of easy and easy login function
Rails migration column changes and so on.
[Java] Personal summary of classes and methods (basic)
rails db: 〇〇 Summary
[Rails] Addition of columns / Change of data type / column name
[Rails] Migration command summary
[Rails] rails db command summary
Basic knowledge of SQL statements
Summary of FileInputStream and BufferedInputStream
Summary of basic functions of ImageJ
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0