Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing only the most popular tags in the acts_as_taggable_on tag cloud

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

like image 369
rugbert Avatar asked Oct 08 '11 15:10

rugbert


2 Answers

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)

like image 144
Frost Avatar answered Nov 07 '22 04:11

Frost


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!

like image 1
Panchew Avatar answered Nov 07 '22 04:11

Panchew