Implement login function using gem'devise' Change to name and password login instead of password and email login.
--Implemented login function using devise --Change to login with name and password
Gemfile
#Added at the bottom
gem 'devise'
Execute the command below the terminal after editing the Gemfile
Terminal
bundle install
rails g devise:install
rails g devise User
rails db:migrate
However, this time I decided to log in by name, so edit the migration file before rails db: migrate.
db/migrate
#t.timestamps null:Add above false
t.string :name
Terminal
rails g devise:view
By the way, in the created file, registrations is a new registration and sessions is a file related to login.
:app/views/devise/sessions/new.html.erb
<h2>Log in</h2>
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true, autocomplete: "name" %>
</div>
(Omitted as there is no change after this)
<% end %>
<%= render "devise/shared/links" %>
Change email to name and email_field to text_field
:app/views/devise/registrations/new.html.erb
#Added above the email div tag
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true, autocomplete: "name" %>
</div>
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :configure_premitted_parameters, if: :devise_controller?
protected
def configure_premitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :email])
devise_parameter_sanitizer.permit(:sign_in, keys: [:name])
end
end
Almost completed with this
Terminal
rails g controller home top
:app/views/home/top.html.erb
<h1>Home#top</h1>
<%= link_to "Log out", destroy_user_session_path, method: :delete %>
I want to be able to log out, so create a logout button using the link_to method. Add the following to application_controller.rb
app/controllers/application_controller.rb
#Add on top of protected
def after_sign_in_path_for(resource)
home_top_path
end
cinfig/initializers/devise.rb
#Uncomment the following around line 49
config.authentication_keys = [:email]
#Change the above email to name
config.authentication_keys = [:name]
Please note that you cannot log in by name without this!
that's all.
Recommended Posts