[RUBY] Implement simple login function in Rails


I am creating a portfolio using Ruby on Rails in order to change jobs from inexperienced to IT engineer.

When creating a portfolio that implements the login function, most of the functions cannot be used without logging in, so you must log in to confirm the function (check your user name and password, or register a new one). It takes time and effort.

Originally, it is a function that is not necessary as an application, but as part of studying, and when you look at your portfolio, we will implement a function that allows you to easily log in so that the employer does not have to take time.

Development environment

Ruby:2.6.3 Ruby on Rails:5.2.0

Before getting into the explanation

I will attach an article that I referred to when implementing the function. -[Easy login / guest login function implementation method (for portfolio)](https://qiita.com/take18k_tech/items/35f9b5883f5be4c6e104 ") It was very helpful. I think that there is no problem if you can refer to here for the basics. Thank you very much. In my case, I didn't use a feature called Devise, so I implemented it in a way that doesn't use Devise. It is assumed that the user is processing with user Model and controller.

1. Create SessionsController


$ rails g controller sessions 

Create SessionsController above

2. Edit SessionsController


class SessionsController < ApplicationController
  def create
    user = User.find_by(name: params[:name])
    if user&.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to :root
      render template: "users/login_form"

  def destroy
    redirect_to :root

#The following guest login actions
  def guest_login
    user = User.guest
    session[:user_id] = user.id
    redirect_to :root, notice: "You have logged in as a guest user."

Since create and destroy are necessary when managing the login function with the sessions controller, they are described. Redirect and render destination can be set arbitrarily. Personal note: &. Returns nil when the left side object is nil, and calls the method on the right side when it is not nil.

The action name can be set arbitrarily. The guest method is defined in the User Model in the next section.

3. Edit User Model


   def self.guest
    find_or_create_by!(name: 'guest') do |user|
      email: "[email protected]",
      birthday: "1990-01-01",
      sex: 3})
      user.password = SecureRandom.urlsafe_base64

In my case, the user table has several columns, so when I log in to guest, I use assign_attributes to embed various information. It can be omitted if it is not necessary.

4. Routing settings


  resource :session, only: [:create, :destroy] do
    post "guest_login", on: :collection

Set the routing to guest_login.

5. Create a link


<%= link_to "Easy login", :guest_login_session, method: :post %>

Embed the above where needed.


With the above, the simple login function can be implemented. The point is ** find_or_create_by! ** in Section 3. You can search for'guest' from the argument name, return the corresponding data if it exists, and create a new one if it doesn't. With this setting, even if the guest user is deleted, you can log in again as'guest'.

To some extent, I created the application and then introduced it additionally, so I think there are some scenes where the explanation is missing. We apologize for any inadequacies. I would appreciate it if you could implement it in a way that suits you by referring to the articles I referred to and other articles.

Finally a digression

This is my first post, but when I wrote the article, I had many opportunities to reconfirm the meaning of the words, which was a great learning experience. I reconfirmed that communicating what I learned will deepen my understanding. In the future, as well as studying, I would like to do my best to post.

Recommended Posts

Implement simple login function in Rails
Implement application function in Rails
Implement follow function in Rails
Implement CSV download function in Rails
Implement login function in Rails simply by name and password (1)
Implement login function in Rails simply by name and password (2)
Implement login function simply with name and password in Rails (3)
[Rails] Function restrictions in devise (login / logout)
[Rails] Implement search function
Implement markdown in Rails
[Rails] A simple way to implement a self-introduction function in your profile
Simple notification function in Rails (only when followed)
[Rails] Implement User search function
Implement LTI authentication in Rails
2 Implement simple parsing in Java
Login function implementation with rails
Implement import process in Rails
[Rails] Implement image posting function
Ruby on Rails <2021> Implementation of simple login function (form_with)
Implement post search function in Rails application (where method)
[Rails] Implement credit card registration / deletion function in PAY.JP
Implement user follow function in Rails (I use Ajax) ②
Implement user follow function in Rails (I use Ajax) ①
Add a search function in Rails.
[rails] Login screen implementation in devise
3 Implement a simple interpreter in Java
Implement tagging function in form object
Implement PHP implode function in Java
Implement a contact form in Rails
[Ruby on Rails] Implement login function by add_token_to_users with API
Login function
1 Implement simple lexical analysis in Java
Implement user registration function and corporate registration function separately in Rails devise
I tried to implement Ajax processing of like function in Rails
Implement star evaluation function in Rails 6 (Webpacker is installed as standard)
How to implement search functionality in Rails
Rails Addition of easy and easy login function
[Rails withdrawal] Create a simple withdrawal function with rails
Try to implement login function with Spring-Boot
Make a login function with Rails anyway
Implemented follow function in Rails (Ajax communication)
How to implement ranking functionality in Rails
Implement button transitions using link_to in Rails
[Rails 6] Ranking function
Implement Rails pagination
[Rails] Category function
Group_by in Rails
Rails follow function
"Teacher, I want to implement a login function in Spring" ① Hello World
[Rails] Notification function
Validation settings for Ruby on Rails login function
Output Hello World in kotlin's simple main function
Create authentication function in Rails application using devise
Implement share button in Rails 6 without using Gem
Try to implement login function with Spring Boot
[Rails] Implementation of retweet function in SNS application
How to implement a like feature in Rails
Implement the Like feature in Ajax with Rails.
Implement iteration in View by rendering collection [Rails]
[Note] Summary of rails login function using devise ①
How to make a follow function in Rails