Creating a Login for your Rails Application

maybe possibly probably one of the times we needed to login
rails g resource user name password_digest
get “/login”, to: users#login
def login
render :login
end
#inside view/user login.html.erb <%= form_tag login_path do %>
<%= label_tag :name
<%= text_field_tag :name %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<%= submit_tag “login” %>
<% end %>
“post “/login”, to: “users#process_login”
def process_login
user = User.find_by(username: params[:username])
if user
session[:user_id] = user.id
redirect_to whatever
else
render :login
end
end
route (get “/logout”), to: “users#logout”
def logout
session.clear
redirect_to :login
end
class User
has_secure_password
validates :name, presence: true, uniqueness: true
end
resources :users, :only [:new, :create]
def new
@user = User.new
end
def create
user = User.new(strong_params)
if user.save
session[:user_id] = user.id
redirect_to whatever
else
render :new
end
end
private
def strong_params
params.require(:user).permit(:name, :password)
end
inside app/views/users new.html.erb
<%= form_for(@user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "submit" %>
<%= end %>
def process_login
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:username])
session[:user_id] = user.id
redirect_to whatever
else
render :login
end
end

--

--

--

Student at The Flatiron School in Washington DC

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Granular Control of “R” Shiny apps with Docker containers and ShinyProxy

GCP Cloud SQL — Recovering an accidentally deleted database/Cloud SQL Instance

Summer of Codeprentice

Trace Exact Location

Web development course in Delhi

Web development course in Delhi

ISC 2017 Computer Science Question 10 solution — ISC Computer Science Question Paper 2017 Solved

Set Up a Free VPN Server in AWS

Regex Cheet sheet

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Adolfo

Adam Adolfo

Student at The Flatiron School in Washington DC

More from Medium

How to install an SSL Certificate on Qmail?

What is NGINX & Why you should use it now?

Number to Word Converter for Arabic and English Languages (number_humanizer gem)

How to add domain to new Lightsail instance