I wanted to add auto complete feature in a form field. I used auto_complete plug-in. It is a great plug-in, very simple to use. In few lines of code, I was able to get this up and running.
1) To install run script/plugin install auto_complete
2) In controller, add auto_complete_for :tag, :name where Tag is a model and name is a field, I wanted my auto complete on.
3) In view add <%= text_field_with_auto_complete :tag, :name %>. The method it implements will search through all the Tags in you records database and do a LIKE comparison on the name column, comparing the name to the contents of the tag[title] form field.
4) I had to reopen auto_plug to fix "Mysql::Error: #23000Column 'name' in where clause is ambiguous". In my case, for auto_complete_for method I was passing :joins condition.
I wanted to show tags for a given model. Both Tag and Model had same column name "name". To fix the problem, I created another plug_in name auto_complete_extended with single class init.rb. In init.rb I reopened auto_complete_for method (as follows):
class ActionController::Base
# Reopening auto_complete_for from auto_complete plug-in
### This is copy of auto_complete_for except for the part in condition where it qualifies column name with table name.
def self.auto_complete_for(object, method, options = {})
define_method("auto_complete_for_#{object}_#{method}") do
find_options = {
:conditions => [ "LOWER(#{object.to_s.pluralize}.#{method}) LIKE ?", '%' + params[object][method].downcase + '%' ],
:order => "#{method} ASC",
:limit => 10 }.merge!(options)
@items = object.to_s.camelize.constantize.find(:all, find_options)
render :inline => "<%= auto_complete_result @items, '#{method}' %>"
end
end
end
Thanks to for the following post. It helped me get started. http://codeintensity.blogspot.com/2008/02/auto-complete-text-fields-in-rails-2.html
Tuesday, July 15, 2008
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment