New bamboo web development

Bamboo blog. Our thoughts on web technology.


ActiveRecord != DataMapper

about 4 years agoby matt

As a follow-up to Rails || Merb, I'm going to highlight some of the differences between ActiveRecord (AR) and Datamapper. Merb is ORM agnostic so you can still use AR if you want to, but I thought I might as well try DataMapper out.

Datamapper (DM) isn't really production ready at the moment as migrations are destructive, but hopefully that'll change in the next few months.

The first thing you'll notice is that in DM the properties of the database are in your model, where in AR they are in a migration.

Take a look at this example DM model:

1 class Post < DataMapper::Base
2   property :title,      :string
3   property :textile,    :text
4   property :created_at, :datetime
5 end
6 
7 rake dm:db:automigrate || DataMapper::Base.auto_migrate!

With AR this would be in a migration, not to dissimilar to this:

 1 class CreatePosts < ActiveRecord::Migration
 2   def self.up
 3   create_table :posts do |t|
 4     t.string :title
 5     t.text   :textile
 6     t.timestamps
 7     end
 8   end
 9 
10   def self.down
11     drop_table :posts
12   end
13 end
14 
15 rake db:migrate

I should point out that just like AR the created_at field is automatically filled in by DataMapper.

DataMapper has a few ActiveRecord impersonations such as the follow methods: [], all, count, create, create!, delete_all, each, find, find_by_sql, find_or_create, first, get, truncate!, destroy!, included, reload, reload!, save

Here is a list of some syntax comparisons:

*The AR way* *The DM way*
User.find(:all) User.all
User.find(10) User[ 10 ]
@user.update_attributes(:name => 'Matt') @user.update_attributes(:name => 'Matt')
User.find(:all, :conditions => :sex = 'Female, :age > 21) User.all(:sex => 'Female', :age.gt =>21)
User.find(:all, :conditions => ["id IN (?)", [1,3,37]] User.all(:id.in => [1,3,37])
has_many :through _not implemented yet_

Something you might want to watch out for, covered by Jon is that DM will only persist changes that it manages, so if you're using virtual attributes you'll need to mark the model as dirty. Also there are currently bugs in finding with conditions on associations and count.