Read more

Traverse an ActiveRecord relation along an association

Henning Koch
February 13, 2013Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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

class Post < ActiveRecord::Base
  belongs_to :author
end

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

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:

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.

Posted by Henning Koch to makandra dev (2013-02-13 11:48)