Autocomplete in rails 2.0
There’s been some changes in the way that Rails 2.0 processes forms and form interaction with Ajax. Here’s a quick write-up on how to use auto completion in Rails 2.0 without a database connection.
In my case, I was parsing an Apache configuration file and displaying VirtualHost entries, but you can use this for just about anything (of course, models work too if you’d like to go against the DB)
First, install the auto complete plugin. Rails 2.0 doesn’t have autocomplete in the core anymore, so you’ll have to create your project with the usual rails myproject syntax, and then enter that directory with cd myproject.
Type “script/plugin install auto_complete” to install the auto complete plugin.
Next, we create a simple class to hold our data. You could parse a file here (say, with File.open()), or pull data from other sources in the initialize function of this class. If you’ve got a model in the database, you can use that.
class Apacheconf
@names = []
def names
@names
end
def initialize
# replace this code later with parsing code
@names = Array.new
@names << “alpha”
@names << “beta”
@names << “gamma”
@names << “delta”
end
end
… then we add some code and CSS to our view for the affiliate/index method in app/views/affiliate/index.rhtml
<html>
<head>
<%= javascript_include_tag :defaults %>
<style>
div.auto_complete {
width: 300px;
background: #fff;
}
div.auto_complete ul {
border: 1px solid #888;
margin: 0px;
padding: 0px;
width: 100%;
list-style-type: none;
}
div.auto_complete ul li {
margin: 0px;
padding: 3px;
}
div.auto_complete ul li.selected {
background-color: #ffb;
}
div.auto_complete ul strong.highlight {
color: #800;
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<% form_tag :action => “edit” do %>
<p><%= text_field ‘affiliate’, ‘name’, :autocomplete => ‘off’ %></p>
<div class=”auto_complete” id=”affiliate_name_auto_complete”></div>
<%= auto_complete_field :affiliate_name,
:url => { :action=>’autocomplete_affiliate_name’ },
:tokens => ‘,’ %>
<%= submit_tag %>
<% end %>
</body>
… and then we insert a very small amount of code into the controler (in app/controllers/affiliate_controler.rb) to handle the Ajax callback:
class AffiliateController < ApplicationController
skip_before_filter :verify_authenticity_token,
nly => [:autocomplete_affiliate_name]
def autocomplete_affiliate_name
# this code is called over and over again by Ajax
#
# the next line does a search through the array for terms starting with the
# specified parameters.
@x = Apacheconf.new.names
@affiliates = @x.select { |v| v =~ /^#{params[:affiliate][:name]}/ }
# don’t render the layout – we only want the partial to be rendered
render :layout=>false
end
end
The beauty of this that with the plugin installed, it takes very little work to get autocomplete working.