mbleigh / acts-as-taggable-on

A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.
http://mbleigh.lighthouseapp.com/projects/10116-acts-as-taggable-on
MIT License
4.97k stars 1.2k forks source link

Tag cloud calculations for a model instance #920

Closed github0013 closed 5 years ago

github0013 commented 6 years ago

Let's say I have User and Post models where

tags

User.first.posts.collect{|post| post.tag_list.to_a }.flatten
=> ["a"]

User.last.posts.collect{|post| post.tag_list.to_a }.flatten
=> ["c", "b", "a"]

tag_counts_on on model

tag_counts_on on Post model gives me this, and I understand it.

Post.tag_counts_on(:tags).to_a
=> [
#<ActsAsTaggableOn::Tag id: 1, name: "a", taggings_count: 2>, 
#<ActsAsTaggableOn::Tag id: 2, name: "b", taggings_count: 1>, 
#<ActsAsTaggableOn::Tag id: 3, name: "c", taggings_count: 1>
]

tag_counts_on on model instance

However, when I do tag_counts_on on Post model instance, the results are unexpected

User.first.posts.tag_counts_on(:tags).to_a
=> [
#<ActsAsTaggableOn::Tag id: 1, name: "a", taggings_count: 2>
]

User.last.posts.tag_counts_on(:tags).to_a
=> [
#<ActsAsTaggableOn::Tag id: 1, name: "a", taggings_count: 2>, 
#<ActsAsTaggableOn::Tag id: 2, name: "b", taggings_count: 1>, 
#<ActsAsTaggableOn::Tag id: 3, name: "c", taggings_count: 1>
]

the taggings_count on both results are 2 instead of 1 that I expected.

It seems it only filters tag names that exist in its instance, but not the taggings_count. taggings_count is rather entire count instead of the number of counts that is saved for the instance.

Is this how it's meant to be done?

stevendaniels commented 5 years ago

You are correct, the taggings_count is the entire count for that tag, not the count for any particular model's usage.

If you wanted to get a count for a particular class, you could try the following:

ActsAsTaggableOn::Tagging.where(taggable_type: "Post").group(:tag_id).select("count(tag_id) tag_count, tag_id").first.tag_count

Alternatively, you could use SQL to get the result you're looking for.

Please close this issue after reviewing this response.