Add Custom Fields to a Devise User Model with a Ruby on Rails Migration

Will Johnson
InstructorWill Johnson

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

When you create a User model with Devise using the command rails generate devise User. Devise will create default columns in the database for your User model. To add your own columns for your users you can create a new Rails migration and add any columns you want for your users.

Instructor: [0:01] Here we have a user model that was created by devise. To see what the columns are in the database, let's go to the Rails console by typing rails c.

[0:15] Let's type in user.connection, and then let's type in user. This will show you the defaults that are in the database for the user table where right now we have email, which is a string, an encrypted password, which is also a string.

[0:37] Let's exit the console. Let's clear that out. Let's run rails g migration add_nick_name_to_users. This is saying that we want to create a migration file that will add a nickname to the users' table. You see that Rails creates a new migration file for us. Let's go to db/migrate, and then the add_nick_name_to-users.rb file, which is our migration file.

[1:22] Inside of the change method, type add_column :users, :nick_name, :string. This will add a column to the users' table, which will be called nick_name, and the type of it is a string. Make sure you save that and go to the terminal. Run rails db:migrate.

[2:03] Now we'll save this new column to the database. Now let's go to the Rails console again by typing rails c, and type user.connection, and then let's type user. Now you see we still have the email, that's a string, the encrypted password, that's a string. Here at the bottom, we have nick_name, which is also a string.

[2:31] To recap, we created a migration file that call add_nick_name_to_users. We added a nick_name column, that was a string, to the users' table.