0

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!

Kathan
  • 1,428
  • 2
  • 15
  • 31

2 Answers2

1

Use this code:

if @articles.blank?
  redirect_to request_path
else
  @results = @articles.results
end
RAJ
  • 9,697
  • 1
  • 33
  • 63
Uday kumar das
  • 1,615
  • 16
  • 33
  • Uday, I saw that you were struggling with code formatting, I have done it for you. :), however the proposed solution seems still fail when `params[:query].present?` will be `false`, which was the original problem @Kathan. – RAJ Apr 10 '15 at 07:24
1

Try this:

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
RAJ
  • 9,697
  • 1
  • 33
  • 63
  • .result still throwing an error. Got it to work with @articles.blank? Thank you for the quick response. – Kathan Apr 10 '15 at 07:11
  • Check my comment: http://stackoverflow.com/questions/29555227/redirect-to-path-if-no-results-found-elasticsearch#comment47261909_29555297 – RAJ Apr 10 '15 at 07:24