About ruby on rails, hackintosh, iphone3g and etc.

Saturday, May 9, 2009

Rails Autocomplete Plugin

To enable Rails Autocomplete Plugin, you need the following steps:

1. Install plugin:

script/plugin install auto_complete

2. Add this line to the controller where auto_complete to be used:

auto_complete_for :contact, :name

3. < %= text_field_with_auto_complete :contact, :name, { :size => 10 }, { :skip_style => false,
:method => :get} % >


Using :method => :get overcomes the problem with InvalidAuthenticityToken.

4. To customize the result, you can override a method in your controller.

def auto_complete_for_contact_name
@user = User.find_by_id(session[:user_id])
re = Regexp.new("^#{params[:contact][:name]}", "i")
find_options = {:conditions => ['company_id = ?', "#{@user.company_id}"],:order => "name ASC" }
@organizations = Contact.find(:all, find_options).collect(&:name).select { |org| org.match re }

render :inline => "< %= content_tag(:ul, @organizations.map { |org| content_tag(:li, h(org)) }) % >"
end


The example above shows that the result will be filtered by company_id and sorted by name.

5. To beauty the autocomplete results, the css below can be helpful.

div.auto_complete {
position:absolute;
width:250px;
background-color:white;
border:1px solid #888;
margin:0px;
padding:0px;
}
li.selected { background-color: #ffb; }

No comments: