Search acts_as_taggable for multiple tags

Hey…I’m trying to search a Model that uses acts_as_taggable for
multiple tags. I’d like to pass in a search string containing a space
delimited tags names (i.e. “tag1 tag2”) and return the objects that have
been tagged by either one of those. Thanks!

Don’t know what version you have but my version has a method
“find_tagged_with” that does just that:

def find_tagged_with(list, user = nil)
      find_by_sql([
        "SELECT #{table_name}.* FROM #{table_name}, tags, taggings " 
  •       "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " 
    
  •       " AND taggings.user_id = " + (user.nil? ? 'taggings.user_id' 
    

:
user.id.to_s) +
" AND taggings.taggable_type = ? " +
" AND taggings.tag_id = tags.id AND tags.name IN (?) ",
acts_as_taggable_options[:taggable_type],
(list.kind_of?(String))
? Tag.parse(list) : list
])
end

On Thursday 10 August 2006 02:52, Nathan P. Verni wrote:

Hey…I’m trying to search a Model that uses acts_as_taggable for multiple
tags. I’d like to pass in a search string containing a space delimited
tags names (i.e. “tag1 tag2”) and return the objects that have been tagged
by either one of those. Thanks!
you’ll have to tweak the find_tagged_with methods sql in
acts_as_taggable.rb
(in the lib dir of the plugin) or override it in you model

iirc what happens is the list of tags passed in gets wrapped like its
one tag
rather than split, so you get

IN (’‘tag1’, ‘tag2’’) # note the double quoting!

rather than

In (‘tag1’, ‘tag2’) # what you want

its down to the find_by_sql parameter interpolation - i think i used the
standard “#{var}” replacement rather than c ‘style’ [“IN (?)”, var] -
just
make sure you parse your params for any nasties first. (i’ve since
rolled my
own hence the ‘if i remember’)

you probably want to take a look at Tag.parse too