I'm using Rails 4.0.2 with jquery-rails (3.1.0) and jquery-ui-rails (4.1.1) gems. I'm trying to add Autocomplete to the search form (using Bootstrap 3.1.0):
<%= form_tag products_path, method: :get, class: 'navbar-form navbar-left' do %>
<div class='form-group'>
<%= text_field_tag :query, params[:query], id: "navbar-search-input", class: 'form-control', placeholder: 'Product name.....' %>
</div>
<%= button_tag(type: 'submit', id: 'navbar-search-btn', class: 'btn btn-default') do %>
<i class='fa fa-search fa-fw'></i> Search
<% end %>
<% end %>
Here are my application JS and CSS files:
application.js
//= require jquery
//= require jquery_ujs
//= require jquery.ui.autocomplete
//= require turbolinks
//= require_tree .
var ready;
ready = (function() {
$('a[href="' + this.location.pathname + '"]').parent().addClass('active');
$("#navbar-search-input").autocomplete({
source: '/products/autocomplete.json',
});
});
$(document).ready(ready);
$(document).on('page:load', ready);
application.css.scss
*= require bootstrap
*= font-kit-rails/ubuntu
*= require jquery.ui.autocomplete
*= require_self
*= require_tree .
Than my controller and route for the autocompletion:
class ProductsController < ApplicationController
def autocomplete
@products = Product.order(:name)
respond_to do |format|
format.html
format.json {
render json: @products.where("name ILIKE ?", "%#{params[:q]}%")
}
end
end
routes.rb
resources :products do
collection do
get 'autocomplete'
end
end
Now with all of this, my json file with all of my products at /products/autocomplete.json
are there. The problem is if I type in anything, it gives me a blank dropdown and if I click on any area of the dropdown it will reset the search form field. Do you know how to get this to work?
EDIT
NOTE: I have a Product named Rice
Started GET "/products/autocomplete.json?term=ric" for 127.0.0.1 at 2014-03-19 10:06:51 -0400
Processing by ProductsController#autocomplete as JSON
Parameters: {"term"=>"ric"}
Product Load (0.9ms) SELECT "products".* FROM "products" WHERE (name ILIKE '%%') ORDER BY "products"."name" ASC
Completed 200 OK in 16ms (Views: 14.3ms | ActiveRecord: 0.9ms | Search: 0.0ms)
def autocomplete
@products = Product.order(:name).where("name LIKE ?", "%#{params[:term]}%")
respond_to do |format|
format.html
format.json {
render json: @products.map(&:name).to_json
}
end
end
Judging by your note, it looks like you're not fetching the param correctly in your controller, so try:
render json: @products.where("name ILIKE ?", "%#{params[:term]}%")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With