Getting started with DataMapper 0.3.0

First, if you think you might need some help, there’s an active community supporting DataMapper through the mailing list and the #datamapper IRC channel on irc.freenode.net.

So lets imagine we’re setting up some models for a blogging app. We’ll keep it nice and simple. The first thing to decide on is what models we want. Post is a given. So is Comment. But let’s mix it up and do Category too.

Install DataMapper

If you have RubyGems installed, pop open your console and install DataMapper.

1 gem install datamapper

Install the DataObjects.rb drivers.

Issue the following command to install your preferred flavor of DataObjects. This is the equivalent to gem install mysql when you installed ActiveRecord.

1 gem install do_mysql # or do_sqlite3 or do_postgres

Require it in your application

1 require 'rubygems'
2 require 'data_mapper'

Specify your database connection

You need make sure this is set before you define your models.

1 DataMapper::Database.setup({
2   :adapter  => 'mysql',
3   :host     => 'localhost',
4   :username => 'root',
5   :password => 'R00tPaswooooord',
6   :database => 'myspiffyblog_development'
7 })

Define your models

The Post model should inherit from DataMapper::Base. The convention with model names is to use the singular, not plural version.

1 class Post < DataMapper::Base
2   property :title, :string
3   property :body, :text
4   property :created_at, :datetime
5 end

You can also mix-in DataMapper through an include.

1 class Post 
2   include DataMapper::Persistence
3   
4   property :title, :string
5   property :body, :text
6   property :created_at, :datetime
7 end

Associations

We want to associate the posts with the categories and comments.

 1 class Category < DataMapper::Base  
 2   property :name, :string
 3 
 4   has_many :posts
 5 end
 6 
 7 class Comment < DataMapper::Base
 8   property :posted_by, :string
 9   property :email, :string
10   property :url, :string
11   property :body, :text
12 
13   belongs_to :post
14 end
15 
16 # Now we re-open our Post class to define the associations.  
17 # This would be best included in with the original definition 
18 # of the class, but for the purposes of our demo, this'll do.
19 class Post
20   has_many :comments
21   belongs_to :category
22 end

Set up your database tables

1 Post.table.create!
2 Category.table.create!
3 Comment.table.create!

This will issue the necessary CREATE statements to define each table according to their properties.

You could also do:

1 DataMapper::Persistence.auto_migrate!