Search code examples
ruby-on-railserbacts-as-taggable-on

How to count the amount of times a tag has been used with ActsAsTaggableOn rails


I have a dashboard in my project where I want to show all the tags I have in my project, along with the number of times those tags have been used. For tagging I use the ActsAsTaggableOn gem on my Post model.

I currently have a variable which shows the most used tags in my tagscontroller:

def index
    @tags = ActsAsTaggableOn::Tag.all.most_used
end

And I can find the amount of tags a certain post has by going in to rails console and running

post = Post.first
post.tag_counts_on(:tags).count

however I can't figure out how to return the number of times each tag has been used on my Post model.

EDIT:

Thanks to Sam's answer below I managed to find the column in the tags model I wanted to call from (using the debug console). To call the amount of times each tag has been used I did:

@tags = ActsAsTaggableOn::Tag.all

In my tags controller and

<% @tags.each do |tag| %>
  <%= tag.name %><%= tag.taggings_count %>
<% end %>

In my view.


Solution

  • According to this and this, you should be able to:

    Post.tag_counts
    

    Given :tags is the "context" you used on the Post model.