0

我在我的rails 4應用中使用searchsearch的elasticsearch。Rails 4使用elasticsearch搜索的鏈接

我剛剛實現了一個'你是否有意思'的功能,它會在拼寫錯誤時向用戶推薦正確的拼寫。

did you mean

什麼是把建議的單詞變成可點擊的鏈接,然後是將搜索,而不是最好的方式?無法找到任何文檔。

這在我看來是「你的意思是」建議其顯示代碼:

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> 
+0

將可點擊鏈接帶到您之前搜索過的同一個動作中,並使用新參數作爲建議詞,這將是最好的方法。 – Deep

+0

感謝您的回覆。你能用正確的代碼回答這個問題嗎?這樣我可以接受作爲答案。 @Deep – Kathan

+0

要回答它,我們將需要您當前的代碼。如果您使用建議實施它,則不會發布代碼。 – Deep

回答

1

我發佈了一些代碼可能會幫助你,你將需要解決任何問題但你會得到一個想法需要做什麼:

<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)返回多個單詞,那麼你需要循環它們併爲它們中的每一個添加錨標籤。

希望這會有所幫助。

+0

精美的作品。非常感謝@Deep – Kathan