filterrific:如何用多个单词搜索查询?

时间:2018-05-23 12:18:07

标签: ruby-on-rails ruby filterrific

我使用filterrific进行过滤。

假设我得到一个locality设置为"纽约"的对象。

使用现有代码,如果我只搜索一个单词,它就可以工作:" New"。如果我写'#34;纽约",什么都没有。

filterrific示例中,过滤器允许用户在"查询"中写入多个单词。

模型

  scope :search_query, lambda { |query|
  return nil  if query.blank?
    terms = query.downcase.split(/\s+/)
    terms = terms.map { |e|
      (e.gsub('*', '%') + '%').gsub(/%+/, '%')
    }
    num_or_conds = 2
    where(
      terms.map { |term|
        "(LOWER(title) LIKE ? OR LOWER(locality) LIKE ?)"
      }.join(' AND '),
      *terms.map { |e| [e] * num_or_conds }.flatten
    )
  }



filterrific(
   default_filter_params: {},
   available_filters: [
     :search_query
   ]
 )

控制器

def index
   @filterrific = initialize_filterrific(
     @ads,
     params[:filterrific]
   ) or return
    @ads = @filterrific.find.page(params[:page])
end

查看

  = form_for_filterrific @filterrific do |f|
    div
      | Search
      = f.text_field :search_query, class: 'skills field w-input filterrific-periodically-observed', placeholder: "Job title, keywords, skills..."

      = f.submit 'GO !', {class: "submit-b w-button"}

修改

日志

 Ad Load (1.2ms)  SELECT  "ads".* FROM "ads" WHERE (publishing_at <= '2018-05-24') AND (expiring_at >= '2018-05-24') AND ((LOWER(title) LIKE 'new%' OR LOWER(locality) LIKE 'new%') AND (LOWER(title) LIKE 'york%' OR LOWER(locality) LIKE 'york%')) LIMIT $1 OFFSET $2  [["LIMIT", 20], ["OFFSET", 0]]

1 个答案:

答案 0 :(得分:0)

可以从SQL日志中看到问题:

...
AND ((LOWER(title) LIKE 'new%' OR LOWER(locality) LIKE 'new%')
AND (LOWER(title) LIKE 'york%' OR LOWER(locality) LIKE 'york%'))

所需的SQL

...
AND ((LOWER(title) LIKE '%new%' OR LOWER(locality) LIKE '%new%')
AND (LOWER(title) LIKE '%york%' OR LOWER(locality) LIKE '%york%'))

因为&#34;新&#34;位于locality start ,它匹配;但因为&#34;约克&#34;不是一开始,它不匹配。

要解决此问题,您可以替换以下行:

(e.gsub('*', '%') + '%').gsub(/%+/, '%')

使用:

('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')