问题
Trying to implement the rails auto_complete plugin to help a user select tags that don't appear on the home page since there will be potentially hundreds of tags and only a small fraction can be displayed.
The way my navigation works is like this: I start with a category show page that displays all articles within that category. When the user clicks a tag, that brings up a tag filter in the url like this:
http://localhost:3000/categories/Stories?tag=scary
This will show all articles in the stories category that have the tag "scary."
Since "scary" is not a popular tag it wouldn't show up on the home page, but if you put it into the autocomplete text field "scary" would show up. I'd like the submit tag to render the same url as above.
But I'm getting something a little different:
http://localhost:3000/categories/ShortStories?tag[name]=scary
Unfortunately this filter won't return anything because that pesky [name] sneaks in there.
Here's my controller code for the autocomplete:
class CategoriesController < ApplicationController
auto_complete_for :tag, :name
And the view
<% form_tag category_path, :method => 'get' do %>
<%= text_field_with_auto_complete :tag, :name, { :size => 15 } %>
<%= submit_tag "Search All Tags", :name => nil %>
<% end %>
The :name seems to be required because auto_complete needs to specify a column name but I want to take it out of the url when I hit submit. Any ideas?
回答1:
Rails 2 and Autocomplete would be a good start and
Railscasts - Auto-Complete Association
回答2:
After some searching I found what I was looking for. This blog post was very helpful getting me on the right path.
So this is what I got:
In the controller:
@search_tags = Tag.find_by_keyword(params[:tag])
respond_to do |format|
format.html
format.js do
render :inline => "<%= auto_complete_result(@search_tags, 'name') %>"
end
end
In the view:
<div id="search">
<% form_tag(category_path(), {:method => :get, :class => "form"}) do %>
<%= text_field_with_auto_complete :tag, :name,
{ :name => "tag", :size => 20 },
{:method => :get, :url => category_path(:format => :js) } %>
<%=submit_tag "Search All Tags", :name => nil%>
<% end -%>
Finally, I added a method to the tag.rb model in vendor/plugins/acts_as_taggable_on_steroids/lib
def self.find_by_keyword(keyword)
if keyword.present?
keyword = "%#{keyword}%"
@search_tags = Tag.all :conditions => ["name like ?", keyword], :order => "name asc", :limit => 10
else
@search_tags = Tag.all :limit => 10, :order => "name asc"
end
end
And it works!
来源:https://stackoverflow.com/questions/1911077/rails-auto-complete-tag-search-filter