I summarized how to change the column name of the table in Rails. The steps are as follows.
① Create migration file ② Edit migration file ③ Reflected in the database
This time, change the column name as follows.
Change before
wheather
After change
weather
Model name | Column name (before change) | Column name (after change) |
---|---|---|
users | wheather | weather |
First, create a migration file to change the column name.
$ rails generate migration rename_ [column name before change] _column_to_ [model name (plural)]
This time
$rails generate migration rename_wheather_column_to_users
Describe as.
A new file will be created in / db / migrate
, so add the change
method and describe the column name you want to change there.
File created this time: 20201115004326_rename_wheather_column_to_users.rb
Describe as follows.
/db/migrate/20201115004326_rename_wheather_column_to_users.rb
class RenameWheatherColumnToUsers < ActiveRecord::Migration[6.0]
def change
rename_column :Model name, :Column name (before change), :Column name (after change)
end
end
In this case, it is described as follows.
/db/migrate/20201115004326_rename_wheather_column_to_users.rb
class RenameWheatherColumnToUsers < ActiveRecord::Migration[6.0]
def change
rename_column :users, :wheather, :weather
end
end
Finally, it is reflected in the database and the column name change is completed.
$rails db:migrate
that's all.
I just mistakenly wrote weather
as weather
, and this kind of work happened (laughs).
Please be careful not to misspell it ☆
Recommended Posts