HowTo: RESTful Autocomplete
October 10, 2008 1 Comment
rails 2.1
1) rails howto_auto_complete
2) cd howto_auto_complete
3)
ruby script/generate scaffold Tag name:string
4)
ruby script/generate scaffold Post title:string body:text tag_id:integer
5)
rake db:migrate
6) test if it works, add data if you want
ruby script/server
7)
ruby script/plugin install auto_complete
8) in tag controller index replace with this:
@tags = Tag.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])
9) in posts.rb put these methods:
belongs_to :tagdef tag_name
tag.name if tag
enddef tag_name=(name)
self.tag = Tag.find_or_create_by_name(name) unless name.blank?
end
10) create an index.js.erb in views/tags:
<%= auto_complete_result @tags, :name %>
(restart server to check http://localhost:3000/tags.js)
11) put this in the forms where you want autocomplete (I put mine in edit and new):
<%= text_field_with_auto_complete :post, :tag_name, { :size => 15 }, { :url => formatted_tags_path(:js), :method => :get, :with => "'search=' + element.value" } %>
12) add in layouts/posts.html.erb:
<%= javascript_include_tag :defaults %>
Notes:
-based on Railcasts episode 102
-since post belongs to tag, the postcontroller magically gets/adds the tag name through the set and get methods in #9, the tag_id is still the one saved in posts table