Rename A Database Column with Ruby on Rails Active Record Migrations

Will Johnson
InstructorWill Johnson

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

If you make a mistake when naming your database column, and have data that you want to keep unchanged. You can use the change method with the rename_column definition in your migrations files to update a single column name in your database.

Will Johnson: [0:00] Let's start off by creating a new rails model. Let's type in rails generate model User name:string email:string.

[0:18] Once we run that, rails will create a migration file. It will create a model file, and as well as two tests.

[0:26] The this one, rails db:migrate. This will create a users table inside of our database.

[0:39] Let's go the db folder, the migrate folder, and then to our migration file, which will start with the timestamp and then create, and the name of the table that we just created.

[0:52] Now as I look inside of the change method, I see that I have a typo on email. I actually put emall.

[1:02] Let's check the database just to see what that looks like. We can do that by going to the terminal and typing in rails c and going to the Rails console. Then type User.connection. Then let's type in User.

[1:19] As you see here, the user that is returned has emall. Let's exit the Rails console by typing exit.

[1:28] In order for us to change this, we would type in rails g, which is short for generation, then type in migration and change email.

[1:42] Rails, as you see, creates a new migration file. We go to our new migration file.

[1:49] Inside of the change method, we would type rename_column and then the name of our table which we want to change, which is users, and then the old column name, which will be emall, because that's our typo, and then the new name we want it to be, which will be email. Make sure you save that. Then run rails db:migrate. That'll save that change to the database.

[2:30] To make sure, let's go to the rails console again by typing rails c User.connection and then User.

[2:43] As you see, now the user that's return says email, so it was successfully updated.

[2:50] To recap what we've done, we created a new model inside of rails, and then that had a typo in it as you see here in the migration file. We created a new migration file using the rails g migration command. We rename the column of the users table from emall to email. Then, we ran rails db:migrate to save it to the database.