Friday, November 26, 2010

Auto Complete Text Box in Rails

Found an Awesome plugin https://github.com/rails/auto_complete for doing this and i made it in 5-10 mins.

Install plugin :

ruby script/plugin install git://github.com/rails/auto_complete.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'
end

Search Query in model:

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

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}"
end

In auto_complete_result method:

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

Regards,
Srikanth

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

No comments: