Rails Autocomplete Tag List

I wanted to make an autocomplete text field on a edit form that listed all of the tags that are already entered in the system. It is quite simple, but I thought I would share it to save some time for someone. Of course we are using acts_as_taggable

The controller :

def auto_complete_for_tag_name
auto_complete_responder_for_tag_name params[:tag][:name]

def auto_complete_responder_for_tag_name(value)
@tag_list = Tag.find(:all,
:conditions => [ ‘LOWER(name) LIKE ?’,
‘%’ + value.downcase + ‘%’ ],
:order => ‘name ASC’,
:limit => 10)

render :partial => ‘tags’


Notice the partial

def edit
@content = Content.find(params[:id])
@tag = Tag.new
@tag.name = @content.tag_list

To retrieve the current tag list you need to make a new Tag object and add the tag list to it.

In my _tag.rhtml partial :

<ul class=”tags”>
<% for tag in @tag_list do -%>
<li class=”contact”><div class=”name”><%=h tag.name %> </div></li>
<% end -%>

In My _form.rhtml

<p>Tags (Seperate with space)<br/>

<%= text_field_with_auto_complete :tag, :name,
{:size =>50, :skip_style => true},
{:indicator =>’searchIndicator’,
:tokens => [‘ ‘, ‘\n’]} %>
<%= image_tag(“/images/indicator2.gif”, :id => ‘searchIndicator’, :style => ‘display:none;’) %>

You will notice that I have added a search indicator, which you will need to have on your system.

Thats how easy it is 🙂



1 comment so far

  1. raulriera on

    This example doesnt work on Rails 2 (even after installing the auto complete plugin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: