I love rails!

My Rails Attempt

HowTo: RESTful Autocomplete

with one 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 :tag

def tag_name
tag.name if tag
end

def 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

Written by pash

October 10, 2008 at 8:35 am

Posted in HowTo

Tagged with , ,

One Response

Subscribe to comments with RSS.

  1. Buenas. siguiendo tu istructivo paso a paso, lo logro ponerlo a funcionar, sera que se me paso algo por alto.

    saludos

    Good. istructivo follow your step by step towards putting it into operation, it will be something that I step aside.

    greetings

    william

    January 8, 2009 at 4:43 pm


Leave a Reply