Im building a search field for my profile model, the search field takes in a list of skills separated by comas and find the profiles that have those skills. The code splits up the string by comas into multiple strings in an array. Now I am trying to find profiles that have all the skills in that array but I can't seem to wrap my head around it. I've tried playing around with PSQL code in where() but I can only seem to get it to work with 1 of the skills.
I am following the advanced search guide by 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
Adavanced search view
<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 %>
Try this query:
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
Try this one:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.