Rails makes 'suggest'-style auto completion on text fields really easy using the text_field_with_auto_complete
method.
In Rails 1.x this method was built into ActionView::Helpers::JavaScriptMacrosHelper
, but for Rails 2.x it was moved to a separate plugin.
Let's say you have a model called Post
which has a text field called title
. In your view, where you would normally use text_field_tag
(or f.text_field
), just use text_field_with_auto_complete
instead:
<%= text_field_with_auto_complete :post, :title %>
Additionally, in PostsController
, you have to make a corresponding declaration:
class PostsController < ApplicationController
auto_complete_for :post, :title
end
What this does behind the scenes is dynamically add an action called auto_complete_for_[object]_[method]
to the controller. In the above example this action will be called auto_complete_for_post_title
.
It's worth pointing out that the find
call used by this auto-generated action will act across all model objects, e.g. Post.find(:all, ...)
. If this isn't the behaviour you want (for example, if want to restrict the search to a specific subset of Post
s based on the logged in user) then you have to define your own auto_complete_for_[object]_[method]
action in your controller.