Kathan
Kathan

Reputation: 1458

Rails 4 Searchkick Suggestions Error

Working on getting a 'did you mean?' functionality integrated with my rails 4 app. I am using searchkick with elasticsearch.

I have finally gotten the did you mean to display when a user misspells a query with this code in the view:

<%= @articles.suggestions %>

However, when there aren't any suggestions, I get undefined method 'suggestions'

Do I need to define suggestions in the controller? I have tried to only display suggestions when they are present using this:

<% if @articles.suggestions.present? %>
  <%= @articles.suggestions %>
<% end %>

but get the same error. What is the best way to go about this? Still very new to searchkick so I appreciate any help.

Here is my search method in the articles_controller:

@articles = Article.search(params[:q], misspellings: {edit_distance: 1}, suggest: true, fields: ["specific^10", "title", "aka", "category", "tags_name", "nutritiontable"], boost_where: {specific: :exact}, page: params[:page], per_page: 12)

and article.rb:

searchkick  autocomplete: ['specific'], suggest: ['specific'], conversions: "conversions"

Upvotes: 1

Views: 396

Answers (2)

ymek
ymek

Reputation: 83

It's worth noting an approach which does not rely on Object#try

<% if @articles.respond_to?(:suggestions) %>
    <%= @articles.suggestions %>
<% end %>

Upvotes: 1

potashin
potashin

Reputation: 44601

You can try:

<%= @articles.try(:suggestions) %>

Upvotes: 2

Related Questions