Search code examples
ruby-on-railsruby-on-rails-3tagsacts-as-taggable-on

Return all tags based on context - ActsAsTaggableOn


I'm using the rails gem acts-as-taggable on, and am tagging posts on two contexts: tags and topics.

To return a hash of all the topics tags used so far for posts I can use the code:

 Post.tag_counts_on(:topics)

However, I have created a certain number of set topics tags, and if some of these topics tags aren't currently being used as tags on posts, then the code above doesn't return the said topics.

I am wondering if there is a way to return all the relevant tags based on context -- I was hoping for a solution along the lines of :

 topics = Tag.topics

To implement the solution, I created a Tag.rb model:

 class Tag < ActiveRecord::Base
   has_many :relationship_topics, :foreign_key => "topic_followed_id", :dependent => :destroy
   has_many :topic_followers, :through => :relationship_topics, :source => :topic_follower
 end

Here I have some code to allow for following topics, but nothing more.

Does anyone know how I could return all the tags based on context?


Solution

  • I have never used acts-as-taggable-on but a quick browse through of the code suggests, you can do:

    # to get all the tags with context topic with counts
    ActsAsTaggableOn::Tagging.
        includes(:tag).
        where(:context => "topics").
        group("tags.name").
        select("tags.name, COUNT(*) as count")
    

    You should probably take a look at ActsAsTaggableOn::Tagging, ActsAsTaggableOn::Tag and the migration file in your db/migrations folder to figure out how you can go about it.

    If you don't want the count, only the tag names:

    tags = ActsAsTaggableOn::Tag.includes(:taggings).
               where("taggings.context = 'topics'").
               select("DISTINCT tags.*")
    
    # usage
    tags.each {|tag| puts tag.name}
    

    I hope that answers your question.