[Ruby] [Rails] Add column to devise

1 minute read

Why did you write

If you create a user authentication with devise, you will have an email and password from the beginning, but you need a name to register as a user. I’m always thinking, so take a note.


  • Already add devise gem
  • You have done rails g devise User

Add a column

When adding a column to DB, it is common to write as follows. For now, let’s name the migration file something we can do to do it.

When you name it, write AddColumnToUsers and it means “Add a column to the user table”, so be careful when adding the next column. In the first place, I think that it means adding columns = DB design properly, but I do not know much about this area, so I would like you to teach me a strong person.

$ rails generate migration Add column name To table name Column to add: data type
$ rails generate migration AddNameToUsers name:string


class AddNameToUsers <ActiveRecord::Migration[5.2]
  def change
    add_column :users, :name, :string
$ rails db:migrate

Modify Controller and View


<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

# Add from here
<div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true %>
 # So far

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "new-password" %>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>

  <div class="actions">
    <%= f.submit "Sign up" %>
<% end %>

<%= render "devise/shared/links" %>

I want to be able to receive the information of the name that flew from View, so ` Add the following to application_controller.rb`.


class ApplicationController <ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])

Add the following code to application.html.erb. current_user is one of the methods provided by devise, and you can get the information of the logged-in user.


<% if current_user.present? %>
  <P> Hello, <% = current_user.name%> san! </p>
<% else %>
  <P> Hello, Guest! </p>
<% end %>

OK if displayed well!

Screenshot 2020-07-22 17.47.14.png

Tags: ,