A brief look at the Active Record pattern

2018, Apr 18    

I think most developers (especially the ones working with Ruby/RoR) know Active Record, or at least its Rails` implementation as it’s shipped by default by the framework and just used in most scenarios. In case you’ve somehow missed it, here’s a short description of this pattern by Martin Fowler:

"An object that wraps a row in a database table or view, encapsulates the database access and adds domain logic on that data."

I think there’s no point of writing yet another post about ActiveRecord in Rails. There are tons of them so if you want to refresh/expand your knowledge, please e.g. read the guides. Instead of diving into its implementations, we’ll take a brief look at when (and when not) to use the pattern itself.

When to use it

Building simple CRUD applications using Active Record pattern is really fast. It is a great choice when our domain logic is very simple. Working with a domain where one class easily matches a database record structure, so we can match one object to one database table, seems to be a perfect scenario for Active Record to use it. In such cases it’s really easy to jump into a project with almost no time, you actually just check the DB schema and have a good overview of what the system is doing, because the database tables are almost a mirror reflection of your system objects. Using, understanding and extending such project is pretty easy. It may be a huge win to use Active Record in some projects, but using it everywhere may not be so fun…

When it may not be a good fit

In more complex systems we have to deal with complicated business logic, which is quite hard to reflect in the database. The Active Record pattern itself assumes that you do not have too much business logic, so there is no clear way to put it in your project along with the AR. The biggest drawback in such situations is that a database becomes tightly coupled with your objects, and it’s hard to efficiently separate it, what leads to bad decisions when it comes to your app architecture. And what comes after it, what is hard to separate, is hard to test. Of course, even in complex systems, a good AR implementation will let you e.g. switch from MySQL to Postgres, but can make your project really hard to understand, test, maintain and extend in other places.

TL;DR

Active Record pattern is great and its Rails` implementation lets you build an easy CRUD application in almost no time. It definitely has lots of advantages, but I think it’s good that Rails` became less reliant on the ActiveRecord. It’s worth to remember that there are alternatives, even in the Rails world, and we can use them when we have a project with more complex business logic.