Showing only the most popular tags in the acts_as_taggable_on tag cloud
Asked Answered
R

2

5

Acts-as-taggable works great and everything but I was wondering if there was a way to restrict the tag cloud to only the most popular tags? Right not it looks like its ordering my cloud by the order in which the tags were created.

But it makes more sense to have the tag cloud show only the most popular tags.

My controller has:

  def styles_tag_cloud
     @tags = Tattoo.tag_counts_on(:styles).limit(40)
  end

and my view has:

<% tag_cloud(styles_tag_cloud, %w(css1 css2 css3 css4)) do |tag, css_class| %>
  <%= link_to tag.name, { :action => :tagged, :controller =>:index, :id => tag.name }, :class => css_class %>
<% end %>

But all this does is display the first 40 tags created, and then sizes each tag according to how many times its used

Radiotelegraph answered 8/10, 2011 at 15:6 Comment(0)
B
7

You can use MyModel.tag_counts_on(:tags) to get a list of tags, ordered by tag count descending (most used tag first) and if you want to limit that to a specific number, you can just append .limit(my_magic_number) to it.

So to get a list of the 10 most popular tags on your Post model you'd do something like this:

@tag_counts = Post.tag_counts_on(:tags).limit(10)

If you then want to see how many times each tag has been used, the objects in @tags each have a count attribute you can look at.

EDIT: (extracted from one of my comments below) ...and if you want to the tags in a specific order (the most used tags first) with some externally defined limit, you can use this: Post.tag_counts_on(:tags).order('count desc').limit(however_many_you_want)

Biogeography answered 8/10, 2011 at 15:36 Comment(3)
tag_counts_on is documented here: github.com/mbleigh/acts-as-taggable-on (search for "Tag cloud calculations" on the page)Biogeography
I updated my question, the tag_counts_on simple grabs all the tags and counts each one. Im trying to either order them by the tag count or only display the most popular tagsRadiotelegraph
Well, then do something like Post.tag_counts_on(:tags).order('count desc').limit(however_many_you_want).Biogeography
U
1

According to the documentation, you just have to pass the options you need for your calculations, in your case (the controller):

  def styles_tag_cloud
     @tags = Tattoo.tag_counts_on(:styles).limit(40)
  end

Your view remains the same. Regards!

Urge answered 23/7, 2012 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.