【发布时间】:2023-01-24 15:50:38
【问题描述】:
我正在尝试使用 first_name、last_name、email、project_name、feature_name 来实现用户记录的搜索功能。 这里 first_name、last_name 和 email 来自一个表(User),project_name 来自表 Project 和 feature_name 来自表 Feature。下面给出了模型关联。我有一个用户索引页面,其中列出了表 User 中的所有用户。需要搜索我们正在输入的用户。
模型用户.rb:
has_many :project_users, dependent: :destroy
has_many :projects, through: :project_users, dependent: :destroy
end```
User have fields of first_name, last_name, email etc(using these three fields for search)
model project.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 have project_name(we search using project name)
model feature.rb
```class Feature < ApplicationRecord
belongs_to :project
end```
Feature have feature_name(with feature_name we need to search)
**What I am look for**
We have params[:search_member] which contains the searched item(first_name, last_name, email, project_name, feature_name
For ex: params[:search_member] = "John"
params[:search_member] = "Project1"
params[:search_member] = "Feature1"
params[:search_member] = "john@gmail.com"
Need a single query which checks the "params[:search_member]" in these three tables(User, Project and Feature) in fields first_name, last_name, email, project_name, and feature_name and return the users of searched value.
Working of associations
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
and
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```
1) If I enter project_name it will return all users of that particular project
2) If I enter first_name, last_name or email return all users of this details
3) If I enter feature name, return all users of project that the feature belongs to
Trying to do in a single joins query
【问题讨论】:
标签: ruby ruby-on-rails-3 join search