This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@doohickies = Doohicky.paginate(:include => {:taggings => :tag}, :conditions => conditions_for_doohickies) |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def conditions_for_doohickies | |
unless params[:search].blank? | |
tags = params[:search].split(/\s*,\s*/) | |
conditions << ['tags.name IN (?)', tags] | |
end | |
conditions | |
end |
And, if you want to return doohickies that have all of the tags (AND) you would do it like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |