Search code examples
ruby-on-railsruby-on-rails-4error-handlingelasticsearchsearchkick

Redirect to path if no results found Elasticsearch


Using elasticsearch with searchkick on rails 4 app.

Trying to redirect to a certain path if no search results found. I recently switched from solr and sunspot over to elasticsearch so still getting familiar with elastic.

I tried using my old code (from 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

The redirecting works when no results found, but if you click the search(submit) button with no query in the search bar it returns an error:

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

Any help would be greatly appreciated. I know it's something simple, but I can't seem to find an answer. Thank you!


Solution

  • Use this code:

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