Introducing devise

Introduction flow of devise with Rails

1. Install Gem and restart the server

2. Create a devise configuration file using commands

3. Create a User model using commands

4. Implementation that changes the button display when not logged in and when logged in

5. Set redirect on controller

devise gem installation

Gemfile


#Omission
gem 'devise'

Terminal


#Start the server
% rails s

Execute the command to create a configuration file

Terminal


#Create devise config file
% rails g devise:install

Execute the command to create a User model

Terminal


#Create User model with devise command
% rails g devise user

Perform migration

Terminal


#Perform migration
% rails db:migrate

Reboot local server

Terminal


# 「ctrl +Quit the local server with "C"

#Start the local server again
% rails s

Prepare redirect process

app/controllers/tweets_controller.rb


class TweetsController < ApplicationController
  before_action :set_tweet, only: [:edit, :show]
  before_action :move_to_index, except: [:index, :show]

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
  end

  private
  def tweet_params
    params.require(:tweet).permit(:name, :image, :text)
  end

  def set_tweet
    @tweet = Tweet.find(params[:id])
  end

  def move_to_index
    unless user_signed_in?
      redirect_to action: :index
    end
  end
end

Run the command to create a view for devise

Terminal


rails g devise:views

Add nickname column as string type to users table

Terminal


#Make sure the directory is pictweet
% pwd

#Create a migration file that adds a nickname column of type string to the users table
% rails g migration AddNicknameToUsers nickname:string

#Execute the created migration
% rails db:migrate

Terminal


# 「ctrl +Quit the local server with "C"

#Start the local server again
% rails s

Edit application_controller.rb

app/controllers/application_controller.rb


class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  private
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname])
  end
end

that's all!

By default, email and password work internally in devise, so if you don't add columns, you don't need to write them in the parameters!

Recommended Posts

Introducing devise
Introducing devise
[Rails] Introducing devise
Introducing RSpec
About devise
Devise procedure
[Rails] devise
Introducing the library
Introducing TDD (success)
[Rails] Introducing jquery
devise user registration
Introducing ActionView :: Component
rails + devise + devise_token_auth
Introducing TDD (Failure)
[Rails] After introducing (intentionally) devise, the command stopped working