Credit: Mauro Cicio
You want to store data in a database, without having to use SQL to create or access the database.
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
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
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 ...