Search code examples
ruby-on-rails-3acts-as-taggable-on

Getting tag count with Act_as_taggable_on not working


I've implemented the acts_as_taggable_on gem and I can see on the db the tag table which tags I have.

I am tagging the model Card, and when I do Card.tag_counts

all I get is

 [#<ActsAsTaggableOn::Tag id: 1, name: "test4">, #<ActsAsTaggableOn::Tag id: 2, name: "you">, #<ActsAsTaggableOn::Tag id: 3, name: "test">, #<ActsAsTaggableOn::Tag id: 4, name: "tyy">, #<ActsAsTaggableOn::Tag id: 5, name: "tetes">]

even though I have some cards with the same tag

I've verified this by Card.all.map{|c| c.tags}

and got

[#<ActsAsTaggableOn::Tag id: 1, name: "test4">], [#<ActsAsTaggableOn::Tag id: 2, name: "you">,  #ActsAsTaggableOn::Tag id: 1, name: "test4">], [#<ActsAsTaggableOn::Tag id: 3, name: "test">,  #ActsAsTaggableOn::Tag id: 2, name: "you">], [#<ActsAsTaggableOn::Tag id: 4, name: "tyy">], [#ActsAsTaggableOn::Tag id: 5, name: "tetes">], [#<ActsAsTaggableOn::Tag id: 2, name: "you">], [#ActsAsTaggableOn::Tag id: 2, name: "you">], [#<ActsAsTaggableOn::Tag id: 2, name: "you">]]

so obivously I have a tag for more than once card.

Why won't Card.tag_counts show me the count, and if its not the way how can I get the tag_count?


Solution

  • You need to actually call .count on the returned Tag objects.

    ActsAsTaggableOn is using a custom select to return the counts, and when one does that, the selected values (count, in this case) are accessible, but don't show up in inspect.