Using Acts_as_taggable to Fetch Tags per Model

Posted by labrat

I was looking at the implementation of tags via Acts\_as\_taggable the plugin. Actually surprised to find out that you couldn't just do SomeModel.tags and find all the tags put on a model. Well, thanks to some excellent work from Tom Fake and Douglas F Shearer it's a trivial fix. Go take a look and fetch code from there. Just one note, Shearer's code is missing a single quote to make it work, the line should read: query << " AND taggings.taggable_type = '#{options[:taggable_type]}'" if options[:taggable_type] != nil Now, we can build on this to make it even more friendly. Find the acts\_as\_taggable.rb file under the lib folder and add this under module SingletonMethods def tags(options = {}) options.merge!(:taggable_type => self.to_s) Tag.tags(options) end So, say you add tags to a Post model, you can fetch tags with: Post.tags And even pass all the usual limits and conditions as shown in the original code. Enjoy. Totally off topic but what's with the wave of spam lately? I'm flattered. NOT. Update: Edited method above to suck less.

Douglas F Shearer :: Modify Acts_As_Taggable to Return Tags By Model

Tag Clouds with acts_as_taggable

Comments

Leave a response

  1. Douglas F ShearerNovember 13, 2006 @ 10:37 PM
    Hey Labratz. Thanks for spotting the error in my code, I removed te stray apostrophe instead of adding it's pair, as that's how it is in my production code, but either is valid. You might want to update this post to save people looking for an error than no longer exists. Also thanks for your tags method, it makes the whole thing seem like less of a hack now.
Comment