Techioz Blog

ユーザー名またはメールアドレスで検索する工夫をする

概要

デバイスのセットアップ後 APIセッションでユーザー名またはメールアドレスでユーザーを取得したいと考えています

ログインをパラメータに渡しましたが、Rails がエラーを吐き出します

User.find_for_database_authentication(:login => params[:username][:email])

モデル上の find_for_database_authentication の上書きはすでに行われています。

def self.find_for_database_authentication(warden_conditions)

誰かが何かヒントを持っていますか?

工夫する

class Api::SessionsController < Devise::SessionsController

  respond_to :json

  def create
    resource = User.find_for_database_authentication(:login => params[:username][:email])



    if resource.valid_password?(params[:login][:password])
      sign_in(:user, resource)

      render :json=> {:auth_token=>resource.authentication_token, :email=>resource.email}, :status => :ok
      return
    end
    invalid_login_attempt
  end
end

解決策

これは、次のように find_for_database_authentication をオーバーライドして行いました。

class User
  def self.find_for_database_authentication(auth_hash)
    self.where("username = :query OR email = :query", query: auth_hash[:email].downcase).first
  end
end

それ以上何も必要ありませんでした。