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.96k stars 1.2k forks source link

Allow related_tags_for to be inclusive #997

Closed ivorpad closed 4 years ago

ivorpad commented 4 years ago

I wanted a list of all related Posts that have certain tags, but I needed all the posts including the instantiated Post.

E.g. in this test: https://github.com/mbleigh/acts-as-taggable-on/blob/59dca73af88d9af53604fcfd06a33b1c87b9457c/spec/acts_as_taggable_on/related_spec.rb#L27-L34

It would be nice if you could pass a boolean to find_related_tags so that it's inclusive.

expect(taggable1.find_related_tags(true)).to include(taggable1)
expect(taggable1.find_related_tags(false)).to_not include(taggable1)

I ended up monkey patching related_tags_for

def related_tags_for(context, klass, options = {})
  tags_to_ignore = Array.wrap(options[:ignore]).map(&:to_s) || []
  tags_to_find = tags_on(context).map { |t| t.name }.reject { |t| tags_to_ignore.include? t }
  exclude = exclude_self(klass, id) if options[:exclude].present?
  related_where(klass, ["#{exclude} #{klass.table_name}.#{klass.primary_key} = #{ActsAsTaggableOn::Tagging.table_name}.taggable_id AND #{ActsAsTaggableOn::Tagging.table_name}.taggable_type = '#{klass.base_class}' AND #{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key} AND #{ActsAsTaggableOn::Tag.table_name}.name IN (?) AND #{ActsAsTaggableOn::Tagging.table_name}.context = ?", tags_to_find, context])
end
ivorpad commented 4 years ago

I think this can be achieved with tagged_with()