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.12. Using Object Relational Mapping with Og

Credit: Mauro Cicio

Problem

You want to store data in a database, without having to use SQL to create or access the database.

Solution

Use the Og (ObjectGraph) library, available as the og gem. Where ActiveRecord has a database-centric approach to object-relational mapping, Og is Ruby-centric. With ActiveRecord, you define the database schema ahead of time and have the library figure out what the Ruby objects should look like. With Og, you define the Ruby objects and let the library take care of creating the database schema.

The only restriction Og imposes on your class definitions is that you must use special versions of the decorator methods for adding attribute accessors. For instance, instead of calling attribute to define accessor methods, you call property.

Here we define a basic schema for a weblog program, like that defined in Recipe 13.11:

	require 'cookbook_dbconnect'
	require 'og'

	class BlogPost
	  property :title, :content, String
	end

	class Comment
	  property :author, :content, String
	  belongs_to : 
og_post,  
BlogPost
	end

	# Now that Comment's been defined, add a reference to it in BlogPost.
	class BlogPost
	  has_many :comments, Comment
	end

After defining the schema, we call the og_connect method defined in the chapter introduction. Og automatically creates any necessary database tables:

	og_connect
	# Og uses the Mysql store.
	# Created table 'ogcomment'.
	# Created table 'ogblogpost'.

Now we can create a blog post and some comments:

 post = BlogPost.new ...

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