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.