[RUBY] [Rails] How to create a table, add a column, and change the column type

Introduction

When I was creating a portfolio and wanted to add columns later, or when I wanted to change the type of the column that was set initially, I did not know what to do, so even if you are a beginner, even if you are a beginner I have summarized it for easy understanding. (At first, I thought I should add or change the existing migration file directly, but that is not correct, so I will create another migration file and describe how to add or change it. )

Creating models and tables

When you create a model with the following command, a migration file for creating the table that this model is in charge of is automatically created together with the model.

$ rails g model [Model name] [Column name]:[Column type]

For example, if you want to create a User model, specify User for [Model Name] and name: string email: string for [Column Name: Column Type]. The command looks like this:

$ rails g model User name:string email:string

When you execute the command, the following migration file will be created.

db/migrate/XXXXXXXXXXXXXX_create_users.rb


class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      
      t.timestamps
    end
  end
end

Confirm that the above file is generated, and execute the migration with the following command.

$ rails db:migrate

The Users table is now created.

Add column

If you want to add columns to an already created table, create a new migration and add it instead of writing directly to the existing migration file.

To create a migration file to add a column, use the following command.

$ rails g migration Add[Column name]To[table name] [Column name]:[Column type]

For example, if you want to add an introduction column (text type) to the existing users table, it will be as follows.

$ rails g migration AddIntroductionToUsers introduction:text

When you execute the command, the following migration file will be created.

db/migrate/XXXXXXXXXXXXXX_add_introduction_to_users.rb


class AddIntroductionToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :introduction, :text
  end
end

Confirm that the above file is generated, and execute the migration with the following command.

$ rails db:migrate

The introduction column (text type) is now added to the users table.

Change column type

If you want to change the column type of an existing table, you can change it by the same procedure as adding a column.

To create a migration file to change the column type, use the following command.

$ rails g migration change_data_[Column name]_to_[table name]

For example, if you want to change the type of the material column of the existing productions table, do as follows.

$ rails g migration change_data_material_to_productions

When you execute the command, a migration file will be created, so add the column type you want to change. For example, if you want to change the type of the material column of the productions table to the integer type, add as follows.

db/migrate/XXXXXXXXXXXXXX_change_data_material_to_productions.rb


class ChangeDataMaterialToProductions < ActiveRecord::Migration[6.0]
<!-- *****Add the following***** -->
  def change
    change_column :productions, :material, :integer
  end
<!-- *****Add more***** -->
end

After the addition is completed, execute the migration with the following command.

$ rails db:migrate

The type of the material column in the productions table is now changed to integer type.

Finally

This article is the first to summarize in Qiita what beginners learned while creating a portfolio.

If there are any mistakes in the content, I would be grateful if you could comment.

Recommended Posts

[Rails] How to create a table, add a column, and change the column type
[Rails] How to change the column name of the table
[Ruby on Rails] How to change the column name
How to add columns to a table
[Rails] Processing after adding a column to the devise table
[rails] How to create a partial template
How to create a registration / update function where the table crosses
[Rails] How to introduce kaminari with Slim and change the design
[Rails] I learned about migration files! (Adding a column to the table)
[Rails] How to create a graph using lazy_high_charts
How to easily create a pull-down in Rails
[Rails] How to create a Twitter share button
When you want to add a string type column with a limited length with the `rails generate migration` command
I want to add a reference type column later
(Ruby on Rails6) How to create models and tables
[Rails] Add column to devise
Create table and add columns
How to create a method
How to dynamically change the column name acquired by MyBatis
How to write a migration from Rails datetime type to date type
How to create a form to select a date from the calendar
How to create a placeholder part to use in the IN clause
I want to create a form to select the [Rails] category
How to add the same Indexes in a nested array
Add a shadow to the Swift Button (and also the circle)
How to run React and Rails on the same server
How to create and launch a Dockerfile for Payara Micro
[Ruby On Rails] How to search and save the data of the parent table from the child table
Preparing to create a Rails application
[Rails] How to add new pages
[Rails 6.0, Docker] I tried to summarize the Docker environment construction and commands necessary to create a portfolio
[Ruby On Rails] How to update the calculated result to an integer type column using update_column
How to add the delete function
Click the [rails] button to create a random alphanumeric password and enter it in the password field
How to create a jar file or war file using the jar command
[Rails] How to get the URL of the transition source and redirect
[Rails 6] How to create a dynamic form input screen using cocoon
[Rails] How to change the page title of the browser for each page
[Rails] How to put a crown mark on the ranking function
Install Rails in the development environment and create a new application
[Reading impression] "How to learn Rails, how to write a book, and how to teach"
[chown] How to change the owner of a file or directory
[Java] How to convert from String to Path type and get the path
(Ruby on Rails6) Create a function to edit the posted content
[Rails 5] How to display the password change screen when using devise
[Swift5] How to create a .gitignore file and the code that should be written by default
[Xcode] How to add a README.md file
Migration file to add comment to Rails table
How to change app name in rails
[Rails] How to use the map method
How to add a new hash / array
How to create a Maven repository for 2020
[Rails] [Memo] When to add = to <%%> and when not
Ransack sort_link How to change the color!
How to find the tens and ones
[Swift5] How to create a splash screen
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Rails] How to log in with a name by adding a devise name column
How to change the maximum and maximum number of POST data in Spark
[Rails 6] cocoon_ Add id and data attributes to the form to be added
How to create a server executable JAR and WAR with Spring gradle