问题
Basically, I want to sort all the tags by the number of taggings they have.
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.
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?
I tried Tag
model, but that doesn't seem to work.
Edit 1
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">]
Which is the 2 tags in the system. Is it ordered? How can I tell how many items were tagged by each?
回答1:
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>...]
You may also use tag_counts_on(scope, options)
which is basically the same.
Also, there is a RailsCast on this topic, explaning this gem:
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}
EDIT for Final Answer Purposes
Or the Rails 3 version of the above query:
tags = Item.tag_counts.order(:count)
来源:https://stackoverflow.com/questions/16451179/using-acts-as-taggable-on-how-do-i-find-the-top-say-10-tags-in-my-app