开发者

Showing only the most popular tags in the acts_as_taggable_on tag cloud

开发者 https://www.devze.com 2023-04-11 20:50 出处:网络
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 th开发者_如

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 th开发者_如何学JAVAe 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


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)


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号