How to get a list of all tags while using the gem 'acts-as-taggable-on' in Rails (not the counts)

The tags are stored in the Tags table, which you access from your program with e.g.

ActsAsTaggableOn::Tag.all

If you need more info on tag usage, there is also the table

ActsAsTaggableOn::Tagging

which contains links to where each tag is being used, including its context

To further apply this to your example, you can use

ActsAsTaggableOn::Tagging.includes(:tag).where(context: 'deshanatags').map { |tagging| { 'id' => tagging.tag_id.to_s, 'name' => tagging.tag.name } }.uniq

Let's explain the various parts in this statement:

  • the 'includes' makes sure the different tags are "eager loaded", in other words, that instead of loading n+1 records, only 2 queries will be done on the database
  • the 'where' limits the records to the ones with the given context
  • the 'map' converts the resulting array of records into a new array, containing the hashes you asked for in your problem, with id mapped to the tag's id, and name mapped to the tag's name
  • finally the 'uniq' makes sure that you don't have doubles in your list

To also cope with your additional problem, being taggins without tag, you could extend the where clause to

where("(context = 'deshanatags') AND (tag_id IS NOT NULL)")

I personally think that both solutions will be slow if you have many tags to retrieve as there are many single select statements. I'd do it like this:

ActsAsTaggableOn::Tagging.includes(:tag).where(context: 'deshanatags').uniq.pluck(:id, :name)

If you're on ruby 1.9+

This way you'll just end up with:

SELECT DISTINCT "taggings"."id", name FROM "taggings" LEFT OUTER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."context" = 'deshanatags'

Quick and easy imo


Using the ActsAsTaggableOn::Tagging model, you can get a list of all tags and filter them down according to context, then format them as follows:

ActsAsTaggableOn::Tagging.all
.where(context: "deshanatags")
.map {|tagging| { "id" => "#{tagging.tag.id}", "name" => tagging.tag.name } }

The where will give us a result of all taggings for a given context, which we then iterate over using map, retrieving the related tag for each tagging in our result and getting the id and name attributes.

Make sure to chain the methods directly (not across several lines) if you're not using ruby 1.9+

You can then call .to_json on the result to get a properly formatted json object that you can use

edit:

I updated the post to clarify what each statement does and also updated the format of our final result to use strings as keys instead of symbols