An extension for Formtastic1 to generate AJAX autocomplete dropdown inputs for associations.
This is in a VERY early stage and needs a lot of work before I’d consider it fit for use
Where Task#user is a :belongs_to association
<% semantic_form_for @task do |form| %>
<% form.inputs do %>
<%= form.input :user, :as => :autocomplete, :url => autocomplete_users_path %>
<% end %>
<% end %>
params[:q] is the search field content.
class UsersController < ApplicationController
def autocomplete
@users = User.find(:all, :conditions => ['name LIKE ?', "%#{params[:q]}%"])
render :layout => false
end
end
<ul>
<%- for user in @users -%>
<%= content_tag :li, h(user.name), :id => "result_#{user.id}" %>
<%- end -%>
</ul>
You must have the formtastic gem added to your application, and the :defaults javascript must be included in your layout.
The default stylesheet can be installed using the generator:
./script/generate formtastic_autocomplete
Don’t forget to add it to your application layout
<%= stylesheet_link_tag 'autocomplete' %>
Test, test, test…
Attempt to port this to unobtrusive javascript, create and provide graceful degradation if possible.
Copyright © 2009 Paul Smith, released under the MIT license