使用acts-as-taggable-on 如何在我的应用程序中找到顶部标签,比如10 个? [英] Using acts-as-taggable-on how do I find the top, say 10, tags in my app?

查看:39
本文介绍了使用acts-as-taggable-on 如何在我的应用程序中找到顶部标签,比如10 个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想按标签数量对所有标签进行排序.

Basically, I want to sort all the tags by the number of taggings they have.

我正在尝试使用标签创建导航.所以我只想显示前 5、10、15、X 个标签,按它们标记的项目数排序.

I am trying to create navigation using the tags. So I want to display just the top 5, 10, 15, X tags sorted by the number of items they have tagged.

所以我无法对模型进行任何操作,也没有控制器可以在其中进行操作 - 我可能只需要在导航视图部分中进行操作.

So I can't do any operation on a model, and there isn't a controller I can do it in either - I may just have to do it in the navigation view partial.

但我什至不知道如何查询acts-as-taggable-on"来让我找到系统中的前 X 个标签.

But I don't even know how to query acts-as-taggable-on to allow me to find the top X tags in the system.

我如何使用作为可标记的行为来做到这一点?

How do I do that with acts-as-taggable-on?

我尝试了 Tag 模型,但这似乎不起作用.

I tried Tag model, but that doesn't seem to work.

编辑 1

当我调用 Item.tag_counts 时,我看到的是:

When I call Item.tag_counts, this is what I see:

> Item.tag_counts
   (17.4ms)  SELECT items.id FROM "items" 
  ActsAsTaggableOn::Tag Load (17.1ms)  SELECT tags.*, taggings.tags_count AS count FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN items ON items.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Item' AND taggings.context = 'tags') AND (taggings.taggable_id IN(13)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
 => [#<ActsAsTaggableOn::Tag id: 2, name: "paper">, #<ActsAsTaggableOn::Tag id: 1, name: "notepad">] 

哪个是系统中的2个标签.是订的吗?我如何知道每个项目标记了多少项?

Which is the 2 tags in the system. Is it ordered? How can I tell how many items were tagged by each?

推荐答案

您可以使用模型类上的 tag_counts 来检索标签列表及其各自的计数.

You can use the tag_counts on the model class to retrieve a list of tags and their individual count.

具有默认技能"范围的用户模型示例(由 文档提供).

Example with User model with default "skill" scope (courtesy of the documentation).

User.skill_counts # => [<Tag name="joking" count=2>,<Tag name="clowning" count=1>...]

你也可以使用tag_counts_on(scope, options),基本相同.

You may also use tag_counts_on(scope, options) which is basically the same.

此外,还有一个关于这个主题的 RailsCast,解释了这个宝石:

Also, there is a RailsCast on this topic, explaning this gem:

问题编辑后Item.tag_counts 的列表是具有 count 属性的标签列表.我不确定它们是否已经排序,但您可以按此属性对它们进行排序,如下所示:

EDIT after question edition: The list you have with Item.tag_counts is a list of tags having a count attribute. I am not sure they are already sorted but you can sort them by this attribute like this:

tags = Item.tag_counts.sort_by {|tag| tag.count}

编辑用于最终答案

或者上面查询的Rails 3版本:

Or the Rails 3 version of the above query:

tags = Item.tag_counts.order(:count)

这篇关于使用acts-as-taggable-on 如何在我的应用程序中找到顶部标签,比如10 个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆