[英]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.