Auto complete in RoR (Ruby on Rails)

Dive to step  5 if you have already running application.

1) Create rails application

rails app_auto_complete

2) Configure your database and set any table say ‘products’.

Assumes that you have products table and name, detail fields are there in table.

3) For quick go scaffold application with

ruby script/generate scaffold Product name:string detail:text

4) Now you have running application , to start application start application

ruby script/server

5) Now install rails plugin from git repo  git://github.com/rails/auto_complete.git
if you have git install please start and get with

git clone git://github.com/rails/auto_complete.git
Put it in ~/vendor/plugins

else download manually  from repo.

6) Ok, now we have plugin for auto complete , check if you have included default javascripts in layout
if not please add in layout.

<%= javascript_include_tag :defaults %>

7) Now open file where you want to put auto complete functionality.Say if in ~app/views/product/new.rhtml

replace line <%= f.text_field :name %>
with <%= text_field_with_auto_complete ‘product’, ‘name’,{}, :skip_style => false  %>

8) Now open products controller and put this line after

class ProductsController < ApplicationController

skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_product_name]

9) Now create method for auto complete

def auto_complete_for_message_to()
@products = Product.find(:all , :conditions = >[“name like (?)”,”%”+params[:product][:name].to_s+”%”])
render :partial => ‘product’
end

10) Step for showing auto compete result.
Create partial file in product folder and name it “_product.rhtml”

and put this code

<ul>
<% for product in @products do %>
<li>
<div><%=h product.name %></div>
</li>
<% end %>
</ul>

11) Finally restart you application and go to url

http://host:port/products/new (For local development)

Have fun !!!!!

For any query please post …..

Advertisements

4 thoughts on “Auto complete in RoR (Ruby on Rails)

  1. Thanks for posting this. You can also install the plugin from your application root by running this command: “ruby script/plugin install git://github.com/rails/auto_complete.git”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s