Separating domain and persistence with repositories
In Chapter 2, Active Models and Records, we discussed two object-relational mapping abstractions, Active Record and Data Mapper, and their differences. Rails obviously goes with the first approach, but that doesn’t mean we cannot derail and use Data Mapper concepts in our code.
To recall, the main difference between Active Record and Data Mapper is that Data Mapper separates models from persistence: models are just enhanced data containers, and other objects are used for querying and storing data (repositories and relations). Thus, there is a clear separation between the domain layer and domain services. This separation gives you more control over data access and transformation at the cost of losing Active Record’s (the library’s) simplicity.
Usually, switching to the Data Mapper paradigm in Ruby on Rails applications comes along with migrating to some other ORM instead of Active Record – for instance...