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

--

--

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