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 :
If you have an instance of MySql available you can connect to it using :
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.
property :id, Integer, :serial => true
property :name, String
property :surname, String
has n, :bills
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 = Customer.new
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.