You're viewing a post from the archive. Don't forget to checkout our latest post HTML5-powered Ajax file uploads

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:


class Post < DataMapper::Base
  property :title,      :string
  property :textile,    :text
  property :created_at, :datetime
end

rake dm:db:automigrate || DataMapper::Base.auto_migrate!

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


class CreatePosts < ActiveRecord::Migration
  def self.up
  create_table :posts do |t|
    t.string :title
    t.text   :textile
    t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

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.