[英]Rails 4 link to search with elasticsearch
我在Rails 4應用程序上使用帶有searchkick的elasticsearch。
我剛剛實現了“您是不是要”功能,當查詢拼寫錯誤時,它將向用戶推薦正確的拼寫。
將建議的單詞變成可點擊的鏈接,然后將其搜索的最佳方法是什么? 找不到有關此操作的任何文檔。
這是我視圖中顯示“您的意思”建議的代碼:
Did you mean: <strong><%= @articles.try(:suggestions).join' ' %></strong>
這是我在articles_controller中的搜索方法:
@articles = Article.search(params[:q], misspellings: {edit_distance: 2}, suggest: true, fields: ["specific^10", "title", "aka", "category", "tags_name", "nutritiontable"], boost_where: {specific: :exact}, page: params[:page], per_page: 12)
這是我用來搜索我的應用程序的表格:
<div class="searchbar" id="sea">
<%= form_tag articles_path, method: :get do %>
<p>
<%= text_field_tag :q, params[:q], id:"complete", name:"q", style:"width:550px; height:34px;", :autofocus => true, class: "form-control", placeholder:"Search... " %><br>
<%= submit_tag "Let's Find Out!", :name => nil, class: "btn btn-default btn-lg", style: "margin-right: 10px;" %>
<%= link_to "Most Popular", articles_path(:most_popular => true), class:"btn btn-default btn-lg" %>
</p>
<% end %>
</div>
我發布了一些可能對您有幫助的代碼,您將需要解決其中的所有問題,但是您將了解需要做什么:
<div class="searchbar" id="sea">
<%= form_tag articles_path, method: :get, id: 'search_form' do %>
<p>
<%= text_field_tag :q, params[:q], id:"complete", name:"q", style:"width:550px; height:34px;", :autofocus => true, class: "form-control", placeholder:"Search... " %><br>
<%= submit_tag "Let's Find Out!", :name => nil, class: "btn btn-default btn-lg", style: "margin-right: 10px;" %>
<%= link_to "Most Popular", articles_path(:most_popular => true), class:"btn btn-default btn-lg" %>
</p>
<% end %>
</div>
我剛剛在表單中添加了一個ID。
Did you mean: <a id='suggested_word'><strong><%= @articles.try(:suggestions).join' ' %></strong></a>
然后在jQuery中:
$("#suggested_word").click(function(){
var word = $(this).text();
$("input#complete").val(word);
$("#search_form").submit();
});
這只是一個粗糙的代碼,需要大量重構。 我所做的是,當任何人單擊建議時,都應該在文本框中輸入建議的單詞,然后使用該單詞提交該表格。 因此它將顯示帶有該單詞的新結果。
現在假設@articles.try(:suggestions)
返回多個單詞,那么您需要循環它們並為每個單詞添加錨標記。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.