我正在嘗試構建基本搜索,其中只有整個搜索字詞顯示結果。目前它顯示基於單詞的結果。在Rails中精確搜索術語
下面是從模型代碼:
def search
find(:all, :conditions => ['term' == "%#{search}%"])
end
對不起提前。我對鐵軌很陌生!
謝謝。
我正在嘗試構建基本搜索,其中只有整個搜索字詞顯示結果。目前它顯示基於單詞的結果。在Rails中精確搜索術語
下面是從模型代碼:
def search
find(:all, :conditions => ['term' == "%#{search}%"])
end
對不起提前。我對鐵軌很陌生!
謝謝。
從"%#{search}%"
中刪除%,因此它是"#{search}"
。
%
是一個匹配包含該單詞的每個結果的通配符。所以"%tea%"
例如會匹配眼淚,nestea和蒸汽,當這不是你想要的。
這應該產生一個精確匹配:
def search find(:all, :conditions => ['term' == "#{search}"]) end
感謝您的支持,但我仍然遇到了麻煩。例如,如果我搜索單個字母「a」或示例,那麼每個列表中都會顯示名稱中帶有字母「a」的所有列表。 – TWill24
它看起來像我的def搜索沒有任何出於某種原因的影響。我刪除了全部內容,並且我仍然得到相同的結果。 下面是從視圖中的代碼: '<%= form_tag root_path,:method =>'get',:class =>「input- group-lg「do%> <%= text_field_tag:search,params [:search],remote:true,:class =>」form-control「,:placeholder =>」Search for the best ...「,: autofocus => true%<%= submit_tag「Search」,:name => nil,remote:true,:class =>「btn search-btn btn-lg」%>'' – TWill24
您的代碼不會有幾個原因的工作。
search
將始終爲nil
。['term' == "%#{search}%"]
條件沒什麼意義,因爲 - 正如我之前所說 - search
未定義,因此條件將與['term' == "%%"]
相同。字符串term
不等於%%
,因此整個條件基本上是:[false]
。我會做這樣的事情:
# in your model
scope :search, -> (q) {
q.present? ? where("column_name LIKE :query", query: "%#{q}%") :none
}
# in your controller
def set_index
@b = Best.search(params[:search]).order(:cached_weighted_score => :desc)
end
試試'找到(:全部:條件=> [ '術語' == 「#{}搜索」])' – Pavan
Rails的什麼版本你使用? – spickermann
我正在使用Rails 5.0.0 – TWill24