Getting started with DataMapper

The most famous and widespread ruby ORM is undoubtly ActiveRecord, due to the fact that it comes in bundle with Ruby on Rails. But, has it often happens, that doesn’t mean it’s the best choice : DataMapper has a number of additional features (lazy loading, strategic eager loading – no need to check for possible select + 1 problems), implements the identity map pattern and it’s WAY faster than its counterpart.
First thing that you need to do is to install the related gem, so open up a command prompt, log in as root and type :

gem install data_mapper

After that you will be able to use the DataMapper module inside your Ruby application just with :

require 'rubygems'
require 'dm-core'

If you have an instance of MySql available you can connect to it using :

DataMapper.setup(:default, 'mysql://user:password@hostname/dbname')

For those of you who are acquainted to (N)Hibernate this is maybe the big point, as there’s no need to write mapping files (or attributes, or whatever). All that you need to leverage DataMapper is to include DataMapper::Resource in your class.

class Customer
include DataMapper::Resource

property :id, Integer, :serial => true
property :name, String
property :surname, String
has n, :bills
belongs_to :customergroup

Convention over configuration : unless you explicitly declare it, tables in the database take the plural declination of your business entity’s name (customer -> customers) and foreign key columns are in the format (parententityname)_id: in this case it will be customergroup_id.
DataMapper implements the active record pattern, so each entity is responsible for its own persistence

my_customer =

Data retrieval is done via class methods, like this:

my_customers = Customer.all
my_customers = Customer.get(4) #gets the customer with id = 4
my_customers = Customer.all(:name => "John", :surname => "Smith") # SELECT * FROM customers WHERE name = "John" AND surname = "Smith"

More on DataMapper’s site. A more detailed quickstart available here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s