0

I'm working on search form in my rails application. Here is what I have now:

My view:

<%= form_tag search_suggestions_path, method: 'get', id: 'all-games-search' do %>
  <%= text_field_tag :games_search, (params[:games_search].present? ? params[:games_search] : nil),
                                   class: 'search-input', placeholder: 'Search games...', autocomplete: 'off' %>
  <ul id="results"></ul>
  <%= button_tag name: nil, class: 'submit-button' %>
<% end %>

Controller:

def search_suggestions
    query = params[:games_search]
    results = if query.present?
                response = []
                Game.where('title ILIKE ?', query.to_s).each do |game|
                  obj = {id: game.id, title: "#{query}"}
                  response << obj
                end
                response
              else
                []
              end
    render json: results
  end

And js:

$('#games_search').bind('change input paste', function() {
    var val = $(this).val();
    $.get('/search_suggestions?games_search=' + val, function (data) {
      $('#results').empty().show();
      $.each(data, function(index, results) {
        $('#results').append('<li>' + results.title + '</li>').click(function () {
          location.href = '/games/' + results.id;
        });
      });
    });
  });

This code works, but it gives me the result, only if I enter the whole game's title. What I need, is to show search results, when the first few symbols of game's title are typed in the search input. Thanks ahead.

Alex Zakruzhetskyi
  • 1,383
  • 2
  • 22
  • 43

1 Answers1

-1

Hi @Alex there has been some failed attempts here. They all tried to use a Rails way of doing it but didn't succeed. See here and here.

However, there is a gem(mezis/fuzzily) which allows you to do this easily.

Game.find_by_fuzzy_name('Mortal Kombat', :limit => 10)

This gem will allow you to do fuzzy search on ActiveRecord objects.

Community
  • 1
  • 1
Jones Agyemang
  • 1,230
  • 16
  • 15