Execute the command with rails g migration add_ column name you want to add_to_ table name of the addition destination
.
For example, if you want to add a column for user_id
to the posts
table, it will be as follows.
$ rails g migration add_user_id_to_posts
Modify the contents of the migration file (db/migrate) created by this.
Since the change method has already been defined, write add_column: table name to add to,: column name to add,: its data type
in it.
def change
add_column :posts, :user_id, :integer
end
Then run rails db: migrate
.
Only when you run it will the table change.
$ rails db:migrate
You have successfully added a column.
Execute the command with rails g migration remove_ column name you want to remove_to_ table name to remove column
.
For example, if you want to delete the user_id
column in the posts
table, it will be as follows.
$ rails g migration remove_user_id_to_posts
Run rails db: migrate
after modifying the contents of the migration file as you would add a column.
def change
remove_column :posts, :user_id, :integer
end
$ rails db:migrate
You have successfully deleted the column.
If you want to empty the database once at the initial stage of development after changing the column, execute the following command.
$ rake db:migrate:reset
The database will be empty.
Recommended Posts