繁体   English   中英

Rails 4链接以使用Elasticsearch搜索

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM