Techioz Blog

複数の要素に基づいてユーザーを検索する

概要

first_name、last_name、email、project_name、feature_name を使用してユーザー レコードの検索機能を実装しようとしています。

ここで、first_name、last_name、および email は 1 つのテーブル (User) からのものであり、project_name はテーブル Project からのものであり、feature_name はテーブル Feature.Association からのものです。以下に示します。

User テーブルのすべてのユーザーをリストするユーザー インデックス ページがあります。入力しているユーザーを検索する検索が必要です。

モデル user.rb:

class User < ApplicationRecord
  has_many :project_users, dependent: :destroy
  has_many :projects, through: :project_users, dependent: :destroy
end

ユーザーには名、姓、電子メールなどのフィールドがあります(これら 3 つのフィールドを検索に使用します)

モデルプロジェクト.rb

class Project < ApplicationRecord
  belongs_to :user
  has_many :project_users, dependent: :destroy
  has_many :features, dependent: :destroy
  has_many :users, through: :project_users, source: :user
end

プロジェクトには project_name があります(プロジェクト名で検索します)

モデルの特徴.rb

class Feature < ApplicationRecord
  belongs_to :project
end

機能には feature_name があります (feature_name で検索する必要があります)

私が探しているもの

検索されたアイテム(first_name、last_name、email、project_name、feature_name)を含むparams[:search_member]があります。

例:

params[:search_member] = "John"
params[:search_member] = "Project1"
params[:search_member] = "Feature1"
params[:search_member] = "[email protected]"

これら 3 つのテーブル (User、Project、Feature) のフィールド first_name、last_name、email、project_name、feature_name の「params[:search_member]」をチェックし、検索された値のユーザーを返す単一のクエリが必要です。

協会の活動

current_user.projects # will return all projects belongs to current user

project.users # return all users belongs to project

feature.project # return project that feature belongs to

そして

feature.project.users # will return all users of projects
def search_all
  if params[:search_member].present?
     #need query here
  else
    User.all
  end
end

単一の結合クエリで実行しようとしています

解決策

これを試してみます

def search_all
  if params[:search_member].present?
    User.includes(projects: :features)
        .where(first_name: params[:search_member])
        .or(User.where(last_name: params[:search_member])
        .or(User.where(email: params[:search_member])
        .or(Project.where(project_name: params[:search_member]))
        .or(Feature.where(feature_name: params[:search_member]))
  else
    User.all
  end
end

それが期待どおりに機能する場合は、さまざまなサブクエリをモデル内のスコープにリファクタリングして、読みやすくします。