0
2

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 3 years have passed since last update.

Rails メールアドレス、パスワード+αでログイン認証する

Last updated at Posted at 2020-07-28

目的

nation_nameプロパティをログインに必要な項目に追加する。

使い方

  • カラムとして存在しないプロパティを追加するattr_accessorメソッドを使ってnation_nameプロパティをユーザーモデルに追加する
user.rb
class User < ApplicationRecord
  #accessor
  attr_accessor :nation_name
  • registration/new.html.erbとsessions/new.html.erbに以下のコードを追記する。
:new.html.erb
<div class="field">
    <%= f.label :国名 %><br />
    <%= f.text_field :nation_name, autofocus: true %>
  </div>
  • パラメーターとして送られるgroup_nameが許可されるようにする
:application.controller
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?
  
  def configure_permitted_parameters
    #sign_in時にnation_nameも許可する
    devise_parameter_sanitizer.permit(:sign_in, keys:[:nation_name])
    #sign_up時にnation_nameも許可する
    devise_parameter_sanitizer.permit(:sign_up, keys:[:nation_name])
    #account_update時にnation_nameも許可する
    devise_parameter_sanitizer.permit(:account_update, keys:[:nation_name])
  end 
end

  • ユーザーの新規登録時にネーションIDが保存されるようにする
user.rb
class User < ApplicationRecord
  #accessor
  attr_accessor :nation_name
  #association
  belongs_to :nation
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable,
          authentication_keys: [:email, :nation_name]
          
  #validation
  before_validation :nation_name_to_id, if: :has_nation_name?
  
  def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    nation_name = conditions.delete(:nation_name)
    nation_id = Nation.where(name: nation_name).first
    email = conditions.delete(:email) || conditions.delete(:unconfirmed_email)

    # devise認証を、複数項目に対応させる
    if nation_id && email
      find_by(nation_id: nation_id, email: email)
    elsif conditions.has_key?(:confirmation_token)
      where(conditions).first
    elsif email
      where(email: email).first
    else
      false
    end
  end

  private
  def has_nation_name?
    nation_name.present?
  end

  def nation_name_to_id
    nation = Nation.where(name: nation_name).first_or_create
    self.nation_id = nation.id
  end

end
0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?