Wednesday, May 07, 2008

will_paginate with acts_as_taggable_on_steroids

How to paginate when searching tags with the combination of will_paginate and acts_as_taggable_on_steroids. Here is the paginate call:

@doohickies = Doohicky.paginate(:include => {:taggings => :tag}, :conditions => conditions_for_doohickies)
view raw gistfile1.rb hosted with ❤ by GitHub


Here, conditions_for_doohickies represents a function that produces the proper conditions from the supplied params. This can, of course, be done as an AND or an OR. If you want to return doohickies that have any of the tags (OR) you would do it like this:

def conditions_for_doohickies
unless params[:search].blank?
tags = params[:search].split(/\s*,\s*/)
conditions << ['tags.name IN (?)', tags]
end
conditions
end
view raw gistfile1.rb hosted with ❤ by GitHub


And, if you want to return doohickies that have all of the tags (AND) you would do it like this:

def conditions_for_doohickies
sql = <<-EOSQL
(SELECT COUNT(*) FROM taggings INNER JOIN tags ON taggings.tag_id = tags.id
WHERE taggings.taggable_type = 'Doohicky' AND
taggings.taggable_id = doohickies.id AND
tags.name IN (?)) = ?
EOSQL
conditions << [sql, tags, tags.size]
end
view raw gistfile1.rb hosted with ❤ by GitHub