Friday, November 26, 2010

Auto Complete Text Box in Rails

Found an Awesome plugin for doing this and i made it in 5-10 mins.

Install plugin :

ruby script/plugin install git://

Use in HTML for Text field:
<%= text_field_with_auto_complete 'phonenumber', 'to',{}, :skip_style => false %>

Controller :

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

def auto_complete_for_phonenumber_to
phonenumber = params[:phonenumber][:to]
@phones = CustomerPhone.phonenumber_search(phonenumber)
render :partial => 'phonenumbers'

Search Query in model:

def self.phonenumber_search(keyword)
find(:all, :conditions=>["phonenumber like ?", "%#{keyword}%"])

View :

Create Partial : "_phone_number.html.erb"

<%= auto_complete_result @phones, :phonenumber %>

Restart your Server & Search. It works.

Note :
If you get undefined method "text_field_with_auto_complete" Error. It means you have not installed the plugin or have not restarted server.

Need to show more than one field ??
Here it is,

In View:
<%= auto_complete_result @phones, :show_field %>

In Model:

def show_field
"#{phonenumber}, #{name}, #{address}"

In auto_complete_result method:

items = { |entry| content_tag("li", phrase ? highlight(entry.show_field, phrase) : h(entry.show_field)) }


Books: Agile Web Development with Rails | Ruby on Rails For Dummies | Beginning Ruby: From Novice to Professional

No comments: