A visual comparison between DAOs and Repo patterns in Rails. The image shows two distinct sides: ‘DAOs’ with database icons and queries, and ‘Repo’ with abstracted data layers. At the center, the Rails logo unites both concepts in a high-tech setting.
Contrasting DAOs and Repos: A Visual Exploration of Data Patterns in Ruby on Rails.

Repository vs DAO Patterns in Rails

A Comparative Analysis with Examples

--

Article based on a comment from a previous article: click here

In Ruby on Rails, understanding design patterns is crucial for creating maintainable and scalable applications. The Repository and Data Access Object (DAO) patterns are widely used for data access layers, but they serve different purposes, especially considering Rails’ robust Object-Relational Mapping (ORM) system, ActiveRecord. Let’s explore these patterns, focusing on how they integrate with Rails’ ORM.

Repository Pattern in Rails

The Repository pattern abstracts the data layer, providing a collection-like interface for accessing domain entities. In Rails, this means abstracting ActiveRecord models, which allows for more flexibility and easier testing.

Example Usage:

Imagine a blogging platform. You have a Post model, and you want to abstract the data access.

class PostRepository

def find_published
Post.where(published: true)
end

def find_by_author(author_id)
Post.where(author_id: author_id)
end

end

Here, PostRepository provides specific methods for querying posts. It abstracts the ActiveRecord queries behind method calls, making the calling code cleaner and more readable.

DAO Pattern in Rails

The DAO pattern is a more granular approach compared to the Repository. It acts as a proxy for more complex queries or insertions, tightly coupling with the model but offering more control over database interactions.

Example Usage:

Continuing with the blogging platform example, you might need complex queries for the Post model.

class PostDAO
def initialize(post)
@post = post
end

def save_with_audit
ActiveRecord::Base.transaction do
@post.save!
Audit.create!(post_id: @post.id, action: "saved")
end
end

def complex_query
# A complex SQL query
end
end

In this case, PostDAO is closely tied to the Post model, handling complex transactions and queries that go beyond simple CRUD operations.

--

--

Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.