Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

13.18. Adding Taggability with a Database Mixin

Problem

Without writing a lot of code, you want to make one of your database tables " taggable"—make it possible to add short strings describing a particular item in the table.

Solution

Og comes complete with a tagging mixin. Just call is Taggable on every class you want to be taggable. Og will create all the necessary tables.

Here's the BlogPost class from Recipe 13.12, only this time it's Taggable. Og automatically creates a Tag class and the necessary database tables:

	require 'cookbook_dbconnect'
	require 'og'
	require 'glue/taggable'

	class BlogPost
	  is Taggable
	  property :title, :content, String
	end
	og_connect

	# Now we can play around with tags.
	post = BlogPost.new
	post.title = 'Some more facts about video games'
	post.tag(['editorial', 'games'])
	
	BlogPost.find_with_tags('games').each { |puts| puts post.title }
	# Some more facts about video games

	Tag.find_by_name('editorial').blog_posts.each { |post| puts post.title }
	# Some more facts about video games

To get this feature in ActiveRecord, you'll need to install the acts_as_taggable gem, and you must create the database tables yourself. Here are the tables necessary to add tags to the ActiveRecord BlogPost class (first described in Recipe 13.11): a generic tags table and a join table connecting it to blog_posts.

 DROP TABLE IF EXISTS tags; CREATE TABLE tags ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(32), PRIMARY KEY (id) ) ENGINE=InnoDB; DROP TABLE IF EXISTS tags_blog_posts; CREATE ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required