mbleigh / acts-as-taggable-on

A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.
http://mbleigh.lighthouseapp.com/projects/10116-acts-as-taggable-on
MIT License
4.97k stars 1.2k forks source link

Easier access to all tags for a Class: any drawback on `class Tagging < ApplicationRecord` ? #1057

Closed francescor closed 2 years ago

francescor commented 2 years ago

While getting all tags for a Class, I've been using the following (which does not scale well):

  class User< ApplicationRecord
    acts_as_taggable
    ...
    def self.all_tag_names
      tag_counts.map(&:name)
    end

What about creating app/models/tagging.rb with

class Tagging < ApplicationRecord
end

so to be able to access (read only) the table taggings directly? e.g.

# all tag_ids for model User
Tagging.where(taggable_type: 'User', context: 'tags').pluck(:tag_id).uniq
francescor commented 2 years ago

mmmh, then I probably ends up creating methods for Taggings that may mix up with the rest.

I ended up querying the db directly

def all_items_with_tags_for_model(my_class)

  sql = "SELECT `taggings`.`taggable_id` FROM `taggings` WHERE `taggings`.`taggable_type` = '#{my_class}' AND `taggings`.`context` = 'tags'"
  result = ActiveRecord::Base.connection.exec_query(sql).rows.flatten
end

any suggestion?

francescor commented 2 years ago

nope, at the end I end up with the same load.

well, I will keep using tag_counts.map(&:name)