768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy

Auto Complete Typing in Text Field [Ruby on Rails]


Before

After


-------------------------
Summary
-------------------------

Auto complete is used to find suitable words automatically with corresponding data you wanted while you type it into your text field (check images above). It's so easy to implement it.


-------------------------
Proof of Concept
-------------------------


Requirement : products_controller.rb (default scaffold script), product.rb (ActiveRecord), categories_controller.rb (for auto searching script), auto_complete plugin and index.js in folder views/categories/

  • Install plugin : ruby script/plugin install http://svn.rubyonrails.org/rails/plugins/auto_complete/
  • Modify your product.rb
class Product < ActiveRecord
belongs_to :category

def category_name
category.name if category
end

def category_name=(name)
self.category = Category.find_or_create_by_name(name) unless name.blank?
end

end

  • Create or Modify your categories_controller.rb at def index
def index

@categories = Category.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])

end

  • Create a new file & add script below in views/categories/index.js.erb or index.rjs.
<%= auto_complete_result @categories, :name %>

  • Open your view which is containing form field for your production controller. Then add text_field_with_auto_complete to your wanted text_field, example :
<%= f.label :category_name %>
<%= text_field_with_auto_complete :product, :category_name, { :size => 15 }, {:url => formatted_categories_path(:js), :method => :get, :with =>" 'search=' + element.value" } %>

#if you get error for
formatted_categories_path
#go to your route.rb then add : map.resources :categories

#if get error on
text_field_with_auto_complete
#
go to your route.rb then add :
#map.resources :products, :collection => {:auto_complete_for_product_category_name => :get }

  • Don't forget to put script below into your layout example application.html.erb/rhtml or production.html.erb/rhtml
<%= javascript_include_tag :defaults %>


Please post me message if you have error. Good Luck.


implementation of http://railscasts.com/episodes/102

2 Response to "Auto Complete Typing in Text Field [Ruby on Rails]"

Ruben said...

I have a problem:
undefined method `formatted_categories_path'
But if i change:
resources :categories
in to
map.resources :categories
i get an error on map
I work with Rails 3.0.3, Hope you can help!

Unknown said...

You should initialize the formatted action into your resources, example:

resources :categories, :collection => {:formatted => [:get, :post]}

if the formatted is requiring an id, the resource should be:

resources :categories, :member => {:formatted => [:get, :post]}

i hope that can help your problem.

 
powered by Blogger