Acts As Taggable Conditions Hack
I’ve been happily using the Ruby on Rails acts_as_taggable plugin for some time now. But recently I had a situation that where I had to hack the plugin. The taggable plugin provides a find_tagged_with method that is used to find all records for a given model with a certain tag. Here is the typical usage of this method:
@post = Post.find_tagged_with ['tag1', 'tag2']
What I needed to do is add some conditions to this method. I wanted to find all post tagged ‘tag1’ or ‘tag2’ that were created by a given user. To do this I needed to hack the acts_as_taggable find_tagged_with method as follows:
def find_tagged_with(list, options = {})
query = "SELECT #{table_name}.* FROM #{table_name}, tags, taggings " +
"WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
"AND taggings.taggable_type = ? " +
"AND taggings.tag_id = tags.id AND tags.name IN (?) "
arr = [query, acts_as_taggable_options[:taggable_type], list]
if options[:conditions] != nil
conditions = options[:conditions]
arr.first << " AND #{conditions.first}"
arr = arr + conditions[1..conditions.size-1]
end
found = find_by_sql(arr)
found.uniq!
found
end
With this code in place, I was able to do what I wanted like this:
@posts = Post.find_tagged_with params[:id], :conditions => ['posts.user_id = ?', session[:user].id]
Technorati Tags: ruby, rubyonrails, ruby on rails, rails plugins, acts_as_taggable, acts as taggable