[英]Use all strings in an array to search through a has_many association
我為個人資料模型構建了一個搜索字段,該搜索字段接受以逗號分隔的技能列表,並找到具有這些技能的資料。 該代碼通過逗號將字符串分成多個數組。 現在,我正在嘗試找到具有該陣列所有技能的配置文件,但似乎無法將其包裹住。 我曾嘗試在where()中使用PSQL代碼,但似乎只能使它與其中一種技能一起使用。
我正在關注ryan bates的高級搜索指南。
Profile.rb
class Profile < ApplicationRecord
belongs_to :user, dependent: :destroy
has_many :educations
has_many :experiences
has_many :skills
has_many :awards
has_many :publications
def owner? user
if self.user == user
return true
else
return false
end
end
end
business_search.rb
class BusinessSearch < ApplicationRecord
def profiles
@profiles ||= find_profiles
end
private
def find_profiles
profiles = Profile.all
if self.skills.present?
profiles = profiles.joins(:skills)
skills_array(self.skills).each do |skill|
profiles = profiles.where('skills.name_en = :q or skills.name_ar = :q', q: skill)
end
end
profiles
end
def skills_array(skills)
return skills.split(/,/)
end
end
business_search_controller.rb
class BusinessSearchesController < ApplicationController
def new
@search = BusinessSearch.new
end
def create
@search = BusinessSearch.create!(search_params)
redirect_to @search
end
def show
search = BusinessSearch.find(params[:id])
@profiles = search.profiles
end
private
def search_params
params.require(:business_search).permit(:first_name, :education_field, :skills)
end
end
進階搜尋檢視
<h1>Advanced Search</h1>
<%= form_for @search do |f| %>
<div class="field">
<%= f.label :skills %><br />
<%= f.text_field :skills %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
試試這個查詢:
def find_profiles
return Profile.all if skills.blank?
Profile.joins(:skills)
.where('skills.name_en IN (:skills) OR skills.name_ar IN (:skills)', skills: skills_array(skills))
.group('profiles.id')
.having('COUNT(skills.id) = ?', skills_array(skills).size)
end
試試這個:
def find_profiles
return Profile.all if skills.blank?
Profile.joins(:skills).where('skills.name_en IN (:skills) OR skills.name_ar IN (:skills)', skills: skills_array(skills))
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.