Posted over 5 years ago. Visible to the public. Repeats.

Traverse an ActiveRecord relation along an association

The Edge Rider gem gives your relations a method #traverse_association which
returns a new relation by "pivoting" around a named association.

Say we have a Post model and each Post belongs to an author:

Copy
class Post < ActiveRecord::Base belongs_to :author end

To turn a relation of posts into a relation of its authors:

Copy
posts = Post.where(:archived => false) authors = posts.traverse_association(:author)

You can traverse multiple associations in a single call.
E.g. to turn a relation of posts into a relation of all posts of their authors:

Copy
posts = Post.where(:archived => false) posts_by_same_authors = posts.traverse_association(:author, :posts)

Implementation note

The traversal is achieved internally by collecting all foreign keys in the current relation
and return a new relation with an IN(...) query (which is very efficient even for many thousand keys).
This means every association that you pivot around will trigger one SQL query.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 2 years ago
by Henning Koch
Keywords:
scope
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more