2017-05-18 66 views
0

在我的應用程序中,我在:title上執行scope/search,查找搜索/過濾器我的記錄。搜索本身工作正常,只是用戶需要精確地編寫title &他們無法搜索:title中的單詞。Ruby on Rails - 在標題內搜索查詢

例如如果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,查詢是:使用im Filterrific gem

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我使用pg gemProduction ENV & sqlite3Development ENV

+0

咋一看說我,你應該使用ILIKE爲PG和sqlite3的 – marmeladze

+0

謝謝@marmeladze,我試着用'ILIKE ',但那麼整個搜索都不起作用。即使之前有效。 – Rubioli

+0

http://railscasts.com/episodes/37-simple-search-form可能是有用的 – Mark

回答

0

正如其在此w3schools articleLIKE作品描述:

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