Custom table name in datamapper

I didn’t know how to do this and it took me a while to find out, so I’m posting it here. Let’s take a look at the following class:

class Author

  property :id      , Serial, :key => true
  property :surname , String, :length => 100
  property :initials, String

And here is the same class, changed to be persisted to a table called my_table_name, of course assuming that the repository in use is default

class Author
  storage_names[:default] = "my_table_name"
  property :id      , Serial, :key => true
  property :surname , String, :length => 100
  property :initials, String

The storage_names class method is in the class DataMapper::Model, you can find the documentation here. It is also possible to call storage_name= but it doesn’t work… just use storage_name[repository] =


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.