rocket_tag
rocket_tag copied to clipboard
List all / search tags for autocomplete
Is there a way to setup a Tag#index controller to output a list of tag names (searchable) for use with an autocomplete field?
ie url for an ajax autocomplete field something like : "/tags.json", { q : "test" }
...or something like that.
I can see in the documentation how to select tags that relate (similar etc) to the original record but not for just searching all tags.
I thought it would be something like:
class TagsController < ApplicationController
respond_to :json
def index
Tag.find(:all, :conditions => ['name LIKE ?', "%#{q}%"])
end
end
match "/tags/index" => "tags#index"
but that didn't work.
Any help appreciated.
I thought about posting this on the SO but thought that if the ability isn't in the gem already then it could be discussed here and put forward here as a possible feature request.
try
def index
RocketTag::Tag.find(:all, :conditions => ['name LIKE ?', "%#{params[:q]}%"])
end
Thanks, that seems to have worked well.
Is there an easy way to order the results by popularity as well?
In our model we have a method like:
def find_top_10_tags tag
self.popular_tags.limit(10).where{name.like "#{tag}%"}
end
In the future we are going to add more logic to find tags that only pertain to a more limited subset of our model (i.e. .where(:category => @category)
).
Thanks. I amended mine to be:
@tags = Project.popular_tags.limit(10).where(['name ILIKE ?', "%#{params[:q].downcase}%"]).order("tags_count desc, name")
I was wrong to try to get all tags rather than tags for the model.
I now get the 10 most popular tags where the name matches my search term (ILIKE is case-insensitive LIKE for Postgres) and order by the count and then by name since popular tags method only orders by count.
@bradphelan, should popular_tags
not order by tags_count desc, name
in case some have the same count?