在我的应用程序中,我正在scope/search
上:title
对我的记录进行搜索/过滤。搜索本身工作正常,唯一的事情是用户需要准确写出title
&他们无法在:title
内搜索单词。
例如,如果title
是: 此搜索很酷,则用户需要开始搜索并拥有完整的句子:此搜索进行搜索,他们无法撰写很酷并获得标题中很酷的记录。
我的scope
看起来像是:
class Post < ActiveRecord::Base
scope :search_query, lambda { |query|
return nil if query.blank?
# condition query, parse into individual keywords
terms = query.downcase.split(/\s+/)
# replace "*" with "%" for wildcard searches,
# append '%', remove duplicate '%'s
terms = terms.map { |e|
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
}
# configure number of OR conditions for provision
# of interpolation arguments. Adjust this if you
# change the number of OR conditions.
num_or_conditions = 1
where(
terms.map {
or_clauses = [
"LOWER(posts.title) LIKE ?"
].join(' OR ')
"(#{ or_clauses })"
}.join(' AND '),
*terms.map { |e| [e] * num_or_conditions }.flatten
)
}
如何制作我的scope/query
,以便用户可以搜索title
中的字词并获取包含他们搜索过的字词的记录?
我尝试使用ILIKE
,但之后搜索停止在开发,我认为因为sqlite
而不能ILIKE
,但是production
搜索有效,但仍然无法搜索标题中的字词。
当我使用LIKE
时,sql
查询是:
SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "posts" WHERE ((LOWER(posts.title) LIKE 'rails%')) LIMIT 50 OFFSET 0) subquery_for_count
当我使用ILIKE
时,查询是:
SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "posts" WHERE ((LOWER(posts.title) ILIKE 'rails%')) LIMIT 50 OFFSET 0) subquery_for_count
SQLite3::SQLException: near "ILIKE": syntax error: SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "posts" WHERE ((LOWER(posts.title) ILIKE 'rails%')) LIMIT 50 OFFSET 0) subquery_for_count
ps:我正在使用Filterrific gem
我将pg gem
用于Production ENV
&amp; sqlite3
Development ENV
答案 0 :(得分:1)
正如此w3schools article中所述,WHERE CustomerName LIKE 'a%' => Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' => Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' => Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' => Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' => Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' => Finds any values that starts with "a" and ends with "o"
的作用如下:
(e.gsub('*', '%') + '%').gsub(/%+/, '%')
我需要将('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')
,更改为: (e.gsub('*', '%') + '%').gsub(/%+/, '%')
。
使用(LOWER(posts.title) ILIKE 'keyword%')
进行搜索时,结果为('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')
,而(LOWER(posts.title) ILIKE '%keyword%')
则为{{1}}