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

Scoping tags by tagged model attributes. #909

Open ChrisCPO opened 6 years ago

ChrisCPO commented 6 years ago

Consider the following.

class Site
  has_many :articles
end

class Article
  acts_as_taggable

  belongs_to :site
end

It would be great to be able to scope an the Article.all_tags query to something like

Article.all_tags(scope: { site_id: 1 })

Looks like this could be easily accomplished by passing the scopes to

class ActsAsTaggableOn::Taggable::Collection
  def generate_tagging_scope_in_clause(tagging_scope, table_name, primary_key, attr_scopes = nil)
    table_name_pkey = "#{table_name}.#{primary_key}"
    if ActsAsTaggableOn::Utils.using_mysql?
      # See https://github.com/mbleigh/acts-as-taggable-on/pull/457 for details
      scoped_ids = pluck(table_name_pkey)
      tagging_scope = tagging_scope.where("#{ActsAsTaggableOn::Tagging.table_name}.taggable_id IN (?)", scoped_ids)
    else
      if attr_scopes.present?
        scopes = {}
        scopes[table_name.to_sym] = attr_scopes
        select_scope = except(:select).select(table_name_pkey).where(scopes)
      else
        select_scope = except(:select).select(table_name_pkey)
      end
      tagging_scope = tagging_scope.where("#{ActsAsTaggableOn::Tagging.table_name}.taggable_id IN(#{safe_to_sql(select_scope)})")
    end

    tagging_scope
  end
end

Needs refactored, also needs mysql, but you get the idea.

stevendaniels commented 5 years ago

@seuros - This should be labeled as a "feature".