Ariejan de Vroom – 21 January 2010
249 words in about 1 minute
With DataMapper, it can be quite a challenge to perform tasks that seem so simple at first. DataMapper is an object-relational mapper (ORM) written in Ruby, with a lot of great features and innovative approaches to common ORM-tasks. But it lacks documentation for some of the less-used features and even the more popular search engines don’t have the answer to all questions.
Note: the following examples have been tested with DataMapper version 0.10.2.
One of the questions I had was how to perform multiple queries within a single (database) transaction, so that I can ‘stage’ a number of database queries and commit (or rollback) them all in one go. Fortunately, after some investigation of the DataMapper source code, it turns out to be an extremely simple task:
1 2 3 4 User.transaction do User.first.update(:name => "John Smith") Address.first.update(:street => "") # Invalid: street must not be blank end
With this code neither the address nor the user will be updated in the database if one of the updates fails. The syntax is actually the same as for the ActiveRecord ORM. However, triggering a rollback is done differently, as can be seen in the following example.
1 2 3 4 5 User.transaction do |t| User.first.update(:name => "John Smith") Address.first.update(:street => "Oak St. 400") t.rollback # Transaction will be rolled back even when updates are OK. end
That’s it for now. I’m sure there are some additional features that I haven’t mentioned here, but this is all I had to know at this point.