【问题标题】:Search first word in a field using filterrific使用 filterrific 搜索字段中的第一个单词
【发布时间】:2019-01-23 04:40:01
【问题描述】:

我正在使用 filterrfic gem 在数据库中搜索组织。我面临的问题是,当我搜索名称以 National 开头的组织时,我会得到所有名称中包含 National 的组织的列表。我想要的是它应该只搜索 name_of_organisation 字段的第一个单词。

组织.rb

def self.search(search)
    if search
        where('name_of_organisation LIKE ?', "%#{search}%")
    else
        all
    end
end


filterrific(
available_filters: [
        :search_query           
 ]
)

 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 = 1
     where(
        terms.map { |term|
            "(LOWER(organisations.name_of_organisation) LIKE ?) 
        }.join(' AND '),
        *terms.map { |e| [e] * num_or_conds }.flatten
    )
}

目前它显示所有组织如下: 国家社会服务 国民服役协会

但我想要的是它应该只搜索 name_of_organisation 字段的第一个单词并只显示 国家社会服务局

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 filterrific


    【解决方案1】:

    尝试更改此行:

    where('name_of_organisation LIKE ?', "%#{search}%")
    

    到:

    where('name_of_organisation LIKE ?', "#{search}%")
    

    请注意删除了搜索字符串中的第一个 %。在这种情况下,% 代表 any sequence of 0 or more characters。通过删除第一个,它应该只搜索以您提供的搜索字符串开头的字符串。

    【讨论】:

    • 知道了。谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多