ruby-on-railsacts-as-taggable-on

In "acts-as-taggable-on", how to get all the tags used in all the instances of a Model?


I have my model class described like this:

class MyModel < ApplicationRecord
  acts_as_taggable_on :tags
end

How to get all the tags used by any instance of this model class?

I tried:

MyModel.tags_on(:tags).pluck(:name)

and it works but it generates a query that includes the ids of all the instances of my model:

SELECT tags.* FROM `tags` JOIN (SELECT `taggings`.`tag_id` FROM `taggings` WHERE (taggings.taggable_type = 'MyModel') AND (taggings.taggable_id IN ( **[ALL THE IDS]** ) GROUP BY `taggings`.`tag_id`) AS taggings ON taggings.tag_id = tags.id

Same with:

MyModel.all_tags.pluck(:name)

I also have tried:

ActsAsTaggableOn::Tag.for_context(:tags).pluck(:name)

But it returns all the tags in the context tags for all the models classes and not only MyModel class


Solution

  • My first thought is to just take one of the queries that's returning all tags and refine it to just your taggable_type:

    ActsAsTaggableOn::Tag.for_context(:tags).where(taggings: { taggable_type: 'MyModel'}).uniq.pluck(:name)