O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.11. Using Object Relational Mapping with ActiveRecord

Problem

You want to store data in a database without having to use SQL to access it.

Solution

Use the ActiveRecord library, available as the activerecord gem. It automatically defines Ruby classes that access the contents of database tables.

As an example, let's create two tables in the MySQL database cookbook (see the chapter introduction for more on creating the database itself). The blog_posts table, defined below in SQL, models a simple weblog containing a number of posts. Each blog post can have a number of comments, so we also define a comments table.

	use cookbook;

	DROP TABLE IF EXISTS blog_posts;
	CREATE TABLE blog_posts (
	  id INT(11) NOT NULL AUTO_INCREMENT,
	  title VARCHAR(200),
	  content TEXT,
	  PRIMARY KEY (id)
	) ENGINE=InnoDB;

	DROP TABLE IF EXISTS comments;
	CREATE TABLE comments (
	  id INT(11) NOT NULL AUTO_INCREMENT,
	  blog_post_id INT(11),
	  author VARCHAR(200),
	  content TEXT,
	  PRIMARY KEY (id)
	) ENGINE=InnoDB;

Here are two Ruby classes to represent those tables, and the relationship between them:

	require 'cookbook_dbconnect'
	activerecord_connect                  # See chapter introduction

	class BlogPost < ActiveRecord::Base
	  has_many :comments
	end

	class Comment < ActiveRecord::Base
	  belongs_to :blog_post
	end

Now you can create entries in the tables without writing any SQL:

 post = BlogPost.create(:title => 'First post', :content => "Here are some pictures of our iguana.") comment = Comment.create(:blog_post => post, :author => 'Alice', :content => "That's ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required