Archive for March, 2007|Monthly archive page

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]
end

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’

end

Notice the partial

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

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 -%>
</ul>

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;’) %>
</p>

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

Thats how easy it is 🙂

Hamza