Bug combining acts_as_taggable_on tagged_with scopes

September 8, 2009

My latest Sogeo work is getting quite a lot of distance out of tagging. With mbleigh’s acts_as_taggable_on I’ve been able to conveniently normalize several different data dimensions down into a tag model.

Modeling this was easy enough, but today I ran into an issue when constructing some of the more sophisticated filtering queries.

acts_as_taggable_on utilizes named scope to provide helpful finder methods, like so:

Location.tagged_with("mytag", :on => :tags)

Easy enough to combine with existing scopes:

Location.include_details.sorted.tagged_with("mytag", :on => :tags)

The problem arises when combining two tagged_with scopes, for example:

Location.tagged_with("mytag", :on => :tags) .tagged_with("mycategory", :on => :categories)

You can read a brief discussion of the problems over on this lighthouse ticket, but the crux of the issue is malformed generated SQL.

Until acts_as_taggable_on is updated, a simple if dreadfully inefficient solution is to call the collection for each tagged_with filter, and then combine the results.

location_scope = Location.include_details.sorted
tag_scope = location_scope. tagged_with("mytag", :on => :tags)
category_scope = location_scope. tagged_with("mycategory", :on => :categories)
category_scope.all(conditions) & tag_scope.all(conditions)

This is a serviceable enough solution for me for now, but if this is still a problem in a few months when my app hits production then I’ll have to start working on a real fix for combining multiple tagged_with helper scopes.

Tags: ,

Leave a Reply

Powered by WP Hashcash