myf
myf

Reputation: 195

What is the most professional way to implement autocomplete in Ruby on Rails?

I would like more to find out what approach is optimal. I would like to have a search form with a well-running autocomplete.

Upvotes: 0

Views: 57

Answers (1)

sadaf2605
sadaf2605

Reputation: 7540

Your controller action of autocomplete would look like following:

  def autocomplete
    @products = Product.order(:name).where("name LIKE ?", "'%#{params[:search][:term]}%'")
    respond_to do |format|
      format.html
      format.json { 
        render json: @products.map(&:name)
      }
    end
  end

You will need to add jquery ui auto complete at your application.js

//= require jquery-ui/autocomplete

And the jquery ui function call would look like somewhat like this:

$( "#search" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "search/auto_complete",
      dataType: "json",
      delay: 2000,
      data: {
        search: request
      },
      success: function( data ) {
        response( data );
      }
    });
  }
  });

Upvotes: 2

Related Questions