使用数组中的所有字符串来搜索 has_many 关联

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))                     
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