[RUBY] [Rails] I learned about migration files! (Adding a column to the table)


As I was working with Rails, I noticed that there were a lot of files and commands that I somehow knew existed, but didn't really understand what they did. One of them is the migration file.

When I make a model, I don't know why the migration file is created, and when I type rails db: migrate, it is reflected as table data in schema.rb ... That was the recognition, but I will dig deeper and explain it!

What is a migration file?

The migration file is the blueprint for creating the database. Also, by executing the migration file, a data table based on the described contents will be generated.

Generate a migration file

When you create a model by typing the following in the terminal, a migration file will also be generated automatically.

Basic syntax

rails g model model name#Here, the model name is "book"


class CreateBooks < ActiveRecord::Migration[5.2]
  def change
    create_table :books do |t|

You can see that only t.timestamps is listed by default in the initial state when the migration file is completed. This will add created_at, which means the creation date and time, and updated_at, which means the update date and time, to the column.

Now let's run the migration file we created! I feel that there are not enough columns that I actually need, but I dare to keep it as it is!

Run the migration file

The created migration file is read by typing the following command in the terminal and reflected in the database.


rails db:migrate

Check the status of the migration file

This time, I created only one migration file. I think that you may create many models at the same time (or rather, I think there are more). In such a case, if you want to check how far the migration file you created is executed, type the following command in the terminal.


rails db:migrate:status

This will print the current migration file status to the terminal.


Status   Migration ID    Migration Name
  up     20201114044025   Create books

The migration file that is up is already executed, so it will not be read even if you enter the rails db: migrate command. So if you edit the migration file that is up when you create a column with the wrong name, it will not be read and it will be meaningless.

Reference: [Rails] Thorough explanation of migration files!

Well, so what if you want to add a new column to the books table you just created? Let's check the schema file for the time being!

What is a schema file?

When the migration is executed, a file called schema.rb will be created in the db folder. Let's take a look at the contents immediately.


ActiveRecord::Schema.define(version: 2020_11_14_044025) do
  create_table "books", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

It seems that the table has been created successfully. The description force :: cascade allows the schema to be reloaded if the foreign key is correct. Now let's add a column called title here!

How to add a column

There are two ways to add columns to an existing table.

  1. Create a new migration file and add columns
  2. Add columns with rails db: rollback

① Create a migration file to add columns

In this case, enter the following command in the terminal


rails g migration Add Column name to add To Table name to add Column name to add:Type

In this case, it looks like this:


rails g migration AddTitleToBooks title:string

Then, the following migration file will be created.

Migration file

class AddTitleToBooks < ActiveRecord::Migration[5.2]
  def change
    add_column :books, :title, :string

After that, run the migration file and the title column will be added to the table.


rails db:migrate

② Add a column with rails db: rollback


rails db:migrate:rollback

Entering this command in the terminal reverts the latest migration file version to what it was before rails db: migrate. In this case, the terminal display changes as follows.


Status   Migration ID    Migration Name
 down   20201114044025    Create books  #It's going from up to down! !! !! !!

In other words, going from up to down will bring the database back to what it was before rails db: migrate. Since we have returned to before db: migrate, we can add the title column to the migration file created first.


class CreateGenres < ActiveRecord::Migration[5.2]
  def change
    create_table :books do |t|
      t.string :title    #Add a title column here! !! !! !!

After that, if you execute the migration file as in pattern (1), the title column will be added.


rails db:migrate


ActiveRecord::Schema.define(version: 2020_11_14_044025) do
  create_table "books", force: :cascade do |t|
    t.string "title"  #A title column has been added! !! !! !!
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

in conclusion

The work of modifying the migration file is often more sensitive than I expected, so I was reminded that I should work on it with a solid understanding of the timing and order. I learned one more thing! !!

Recommended Posts

[Rails] I learned about migration files! (Adding a column to the table)
[Rails] Processing after adding a column to the devise table
[Rails] About migration files
[Rails] How to create a table, add a column, and change the column type
[Rails] I learned about the difference between resources and resources
[Rails] How to change the column name of the table
I learned about the existence of a gemspec file
I want to create a form to select the [Rails] category
About the language to be learned
Migration file to add comment to Rails table
[Rails] How to log in with a name by adding a devise name column
I thought about the best way to create a ValueObject in Ruby
When you want to add a string type column with a limited length with the `rails generate migration` command
[Personal memo] I learned a little about modifiers
A note about adding Junit 4 to Android Studio
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to organize the session in Rails
[Rails] I learned about database data type types!
The code I used to connect Rails 3 to PostgreSQL 10
[Beginner] What I learned when trying to introduce bootstrap to the rails6 app without using a CDN [Asset pipeline]
[Ruby] When adding a null constraint to a table
How to make a unique combination of data in the rails intermediate table
A note about the Rails and Vue process
Rails "How to delete NO FILE migration files"
[Rails] I want to display the link destination of link_to in a separate tab
Tokoro I rewrote in the migration from Wicket 7 to 8
I tried to decorate the simple calendar a little
[Ruby on Rails] How to change the column name
I want to use a little icon in Rails
[Rails] I don't know how to use the model ...
I want to define a function in Rails Console
A story about trying hard to decompile JAR files
I want to add a reference type column later
A memorandum about table data types and commands (Rails)
I want to add a delete function to the comment function
About the error that occurred when adding the column name in rails (rails db: migrate, rails db: rollback, add)
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
[Rails 6.0, Docker] I tried to summarize the Docker environment construction and commands necessary to create a portfolio
[Beginner] I want to modify the migration file-How to use rollback-
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried adding a separator line to TabLayout on Android
[Rails] [bootstrap] I want to change the font size responsively
How to write a migration from Rails datetime type to date type
[Rails] I tried to create a mini app with FullCalendar
I want to call a method and count the number
A note about the seed function of Ruby on Rails
I tried using Hotwire to make Rails 6.1 scaffold a SPA
A story I was addicted to in Rails validation settings
A validation error occurred when saving to the intermediate table.
I want to give a class name to the select attribute
[Ruby] I want to reverse the order of the hash table
[Controller] I want to retrieve the numerical value of a specific column from the DB (my memo)
How to deal with the type that I thought about writing a Java program for 2 years
about the where method (rails)
A note about the scope
[Rails] Add column to devise
About adding a like function
[Rails] Delete the migration file
How to rollback migration files
What I learned about Kotlin
I want to recursively search for files under a specific directory