如果没有找到 Elasticsearch 的结果,则重定向到路径

Redirect to path if no results found Elasticsearch

在 rails 4 个应用程序上使用带有 searchkick 的 elasticsearch

如果没有找到搜索结果,尝试重定向到特定路径。我最近从 solr 和 sunspot 切换到 elasticsearch,所以仍然熟悉弹性。

我尝试使用我的旧代码(来自 sunspot):

def index
  if params[:query].present?
    @articles = Article.search(params[:query], misspellings: {edit_distance: 1})
  else
    @articles = Article.all
  end

   if @articles.results.any?
     @results = @articles.results
   else
     return redirect_to request_path
   end
end

重定向在没有找到结果时有效,但如果您单击搜索(提交)按钮时搜索栏中没有任何查询,它 returns 一个错误:

undefined method `results' for #<Article::ActiveRecord_Relation:0x00000102300d10>

如有任何帮助,我们将不胜感激。我知道这很简单,但我似乎找不到答案。谢谢!

使用此代码:

if @articles.blank?
  redirect_to request_path
else
  @results = @articles.results
end

试试这个:

if @articles.respond_to?(:results) # if we got results from ElasticSearch
   @results = @articles.results
elsif @articles.present? # if user has entered blank string ('@articles = Article.all' case)
   @results = @articles
else
   return redirect_to request_path
end