--Create a Session controller
MacBook % rails g controller Sessions new
--Edit the routes file as below
config/routes
Rails.application.routes.draw do
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
~
--Next, create a login form. This time it is a direct writing without using Bootstrap etc.
app/views/sessions/new.html.erb
<body>
<h1>Login</h1>
<%= form_for(:session, url: login_path) do |f| %>
<div class="input-name">
<%= f.label :password, 'Room name' %>
<%= f.text_field :name, placeholder: "Please enter the name of the room" %>
</div>
<div class="form-group">
<%= f.label :password, 'password' %>
<%= f.password_field :password, placeholder: 'Please enter your password' %>
<%= f.submit 'Login' %>
</div>
<% end %>
</body>
--Create a form and access http: // localhost: 3000 / login to check --Once confirmed, then add create and destroy actions to the controller actions
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
room = Room.find_by(name: params[:session][:name])
if room && room.authenticate(params[:session][:password])
else
end
end
def destroy
end
end
--Write the process when login fails in the create action. (Bootstrap etc. are not used)
app/controllers/sessions_controller.rb
~
def create
room = Room.find_by(name: params[:session][:name])
if room && room.authenticate(params[:session][:password])
else
flash[:alert] = 'The name or password is wrong'
redirect_to '/login'
end
end
~
--Added session helper that automatically expires when you close the browser
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include SessionsHelper
end
--Define helper method and log_in method
app/helpers/sessions_helper.rb
module SessionsHelper
#Store encrypted roomID in temporary cookies in the browser
def log_in(room)
session[:room_id] = room.id
end
end
--Now you can log in, so define the create action
/app/controllers/sessions_controller.rb
~
def create
room = Room.find_by(name: params[:session][:name])
if room && room.authenticate(params[:session][:password])
log_in room
redirect_to receptions_path
else
flash[:alert] = 'The name or password is wrong'
redirect_to '/login'
end
end
~
(https://qiita.com/yongjugithub/items/dbb880f085f99cc9af93)
Recommended Posts