Showing only the most popular tags in the acts_as_

2019-04-08 14:35发布

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

2条回答
该账号已被封号
2楼-- · 2019-04-08 15:00

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!

查看更多
唯我独甜
3楼-- · 2019-04-08 15:16

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)

查看更多
登录 后发表回答