When you create user authentication with devise, you will have email and password from the beginning, but you need a name to register as a user. I always think, so take a note.
--Already added the devise gem
--It must be rails g devise User
When adding a column to the DB, it is common to write as follows. For now, give the migration file a name that tells you what the migration file does.
When naming it, if you write ʻAddColumnToUsers` and it means something like" add a column to the user table ", be careful because the name will be a problem when you add the next column. In the first place, I think that it is necessary to add columns = DB design, but I am still inexperienced in this area, so please tell me who is strong.
$rails generate migration Add Column name To Table name Column to add:Data type
$ rails generate migration AddNameToUsers name:string
XXXXXXXXXXX_add_name_to_users.rb
class AddNameToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :name, :string
  end
end
$ rails db:migrate
erb:registrations/new.html.erb
<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 %>
  </div>
	#So far
  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>
  <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>
  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% 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.
application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end
end
Write the following code in ʻapplication.html.erb.  current_user` is one of the methods provided by devise, and you can get the information of the logged-in user.
erb:application.html.erb
<% if current_user.present? %>
  <p>Hello,<%= current_user.name %>San!</p>
<% else %>
  <p>Hello, Guest!</p>
<% end %>
If it is displayed well, it's OK!
        Recommended Posts