我在Rails 4应用程序上使用带有searchkick的elasticsearch。
我刚刚实现了“您是不是要”功能,当查询拼写错误时,它将向用户推荐正确的拼写。
将建议的单词变成可点击的链接,然后搜索该链接的最佳方法是什么?找不到有关此操作的任何文档。
这是我 View 中显示“您的意思”建议的代码:
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)
返回多个单词,那么您需要循环它们并为每个单词添加 anchor 标记。希望这可以帮助。
关于ruby-on-rails - Rails 4链接以使用Elasticsearch搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31498144/