I have implement jQuery-ui autocomplete in my Rails app and it works fine, but i want also the results to be links to the products (e.g. products/1). Any idea how can i do it?
jQuery code in coffeescript:
$(document).on "page:change", ->
$(".header-search-input").autocomplete(
minLength: 2,
source: $(".header-search-input").data('autocomplete-source')
select: (event, ui) ->
$(".header-search-input").val ui.item.label
).autocomplete('instance')._renderItem = (ul, item) ->
result = item.label.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' + $.ui.autocomplete.escapeRegex(@term) + ')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong>$1</strong>')
$('<li>').append('<a>' + result + '</a>').appendTo ul
return
View:
<ul class="nav navbar-nav navbar-left" id="header-search">
<%= form_tag search_path, class: "navbar-form navbar-left list-inline", method: :get do |f| %>
<li class="form-group">
<%= text_field_tag :q, params[:q], class: "form-control margdown header-search-input", placeholder: "Search", data: { autocomplete_source: products_path(:json) } %>
</li>
<li><%= submit_tag "Submit", class: "btn btn-info shake", name: nil %></li>
<% end %>
</ul>
Controller:
def index
if params[:term]
@products = Product.order(:name).where(Product.arel_table[:name].matches("%#{params[:term]}%"))
response = (Hash[@products.map { |u| [u.name, u.id] }])
else
@products = Product.all.where.not(quantity: 0).order(created_at: :desc).paginate(page: params[:page], per_page: 9)
end
respond_to do |format|
format.html
format.json { render json: response.keys }
end
end
I have create a hash as you can see at the controller, with pairs of names and ids, to get the id of the corresponding product name in the view. (You can ignore it is just a thought.) The problem is that i don't know how to do this.