LoginSignup
0

More than 3 years have passed since last update.

【Rails】メールアドレスを記憶する

Posted at

ログインフォームに「次回からメールアドレスの入力を省略する」というチェックボックスをつけて、次回ログインフォームにアクセスした時にメールアドレスが自動で入力される機能を実装したので、実装方法を記録します。

全体の流れ

  • ログインフォームにチェックボックスをを設置
  • チェックされた状態でログインしたら、メールアドレスを暗号化してcookieに保存
  • 次回以降のログイン時、cookieにメールアドレスが保存されているかを確認して、あれば利用
  • チェックを外した状態でログインしたら、cookieに保存されているメールアドレスを削除

Controller

def create
  customer = Customer.find_by(email: params[:session][:email].downcase)
  if customer&.authenticate(params[:session][:password])
    if params[:session][:remember] == '1'
     #cookieを登録
      cookies.permanent.signed[:wbEmail] = params[:session][:email]
    else
     #cookieを削除
      cookies.permanent.signed[:wbEmail] = nil
    end
    log_in customer
    flash[:success] = 'ログインしました'
    redirect_to root_url
  else
    flash.now[:danger] = 'メールアドレスとパスワードの組み合わせが正しくありません'
    render 'new'
  end
end

ログインフォーム

<%= form_with scope: :session, url: login_path, local: true do |f| %>
    <label>メールアドレス</label>
    <% if cookies.permanent[:Email].blank? %>
    <%= f.email_field :email %>
    <% else %>
    <%= f.email_field :email, value: cookies.permanent.signed[:Email] %>
    <% end %>

    <label>パスワード</label>
    <%= f.password_field :password %>

    <% if cookies.permanent[:Email].blank? %>
    <%= f.check_box :remember, id: "check1" %>
    <% else %>
      <%= f.check_box :remember, id: "check1", checked: true %>
    <% end %>
    <label for="check1">次回からメールアドレスの入力を省略する</label>

  <%= f.submit "ログイン" %>
<% end %>

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
0