1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでログイン機能の実装

Last updated at Posted at 2019-05-02

ユーザ登録機能の作成##

Model作成####

$ rails g model User name email password_digest
  • password_digest => パスワードを暗号化
class User < ApplicationRecord
  has_secure_password
end

(app/model/user.rb)

  • has_secure_password => 有効にする
  • バリデーション追加
gem 'bcrypt','~>3.1.7'

(Gemfile)

  • bcryptインストール(コメントアウト外す)
$ bundle install

ルーティング設定####

resources :users, only: [:index, :show, :new, :create]
  • onlyで必要なアクションを指定

Controller作成####

rails g controller users index show new create

index show new createを指定するとこで必要なControllerとViewファイルを自動生成

ユーザ登録ページ作成####

Controller

def new
@user = User.new
end

View

<%= form_with(model: @user, local: true) do |f| %>
  <%= f.label :name, "名前" %>
  <%= f.text_field :name, class: "form-control" %>
  • その他のカラムも同様に作成する

ログイン機能の作成##

ルーティング設定####

get "login", to: "sessions#new"
post "login", to: "sessions#create"
delete "logout", to: "sessions#destroy"

Controller作成####

$ rails g controller sessions new create destroy
def new
end

def create
  email = [:session][:email].downcase
  password = [:session][:password]
  if login(emial, password)
    flash[:success] = ""
    redirect_to root_path
  else
    flash.now[:danger] = ""
    render "new"
  end 

def destroy  
end
  • params[:session][:email].downcaseでフォームデータを取得できる
  • loginメソッド => trueかfalseを返す
private
  def login(email, password)
    @user = User.find_by(email: email)
    if @user && @user.authenticate(password)
      session[:user_id] = @user.id
      return true
    else
      return false
    end 
  end
  • 入力フォームと同じemailを持つユーザを検索し@userに代入する。見つからなければnilを代入する。

  • ユーザの情報があり、そのユーザの持つパスワードと入力パスワードが一致した場合true扱い

ログインView作成####

<%= form_with(url: login_path, scope: :session, local: true) do |f| %>
  <%= f.label :email, "email" %>
  <%= f.email_field :email, class: "form-control" %>
<% end %>
  • Modelがない場合、url:を使う
  • scope: :session => フォームデータが:sessionに入る
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?