【Rails】Mongoidで一部の列のみを指定して検索を行いたい場合


概要

RailsでMongoDBを使用する際、一部のキーのみ指定してmodelから指定したキーで検索する方法を記載します。

前提

  • Mongoidを使用します。MongoidについてはRailsでActiveRecordの代わりにMongoidを使うを参照ください。
  • 今回、以下のようなUserモデルを使用します。emailを検索条件にして、_idpassword_digeststatusのみを抽出します。
user.rb
class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include ActiveModel::SecurePassword

  field :_id, type: String, overwrite: true
  field :email, type: String
  field :name, type: String
  field :status, type: String
  field :role, type: String
  field :gender, type: String
  field :phone_number, type: String
end

実装サンプル

  • where句にemailの条件を設定して、only句で列の絞り込みを行います。
email_auth_controller.rb
class EmailAuthController < ApplicationController

  def email_auth
    #  レコードを抽出するクエリ
    find_by_email_user = User.where(email: email_auth_param[:email]).only(:_id, :password_digest, :status)
    if find_by_email_user.empty?
      render json: { message: "ユーザが見つからなかったよ" }
    else
      # 今回はemailで一意になる前提
      user = find_by_email_user[0]
      if user.status != "active"
        render json: { message: "ステータスが有効じゃないよ" }
      # authenticateメソッドも使える
      elsif !user.authenticate(email_auth[:password])
        render json: { message: "パスワードが違うよ" }
      else
        render json:  { message: "認証OK" }
      end
    end

  def email_auth_param
    params.require(:email_auth).permit(:email, :password)
  end

end