Today I Learned

hashrocket A Hashrocket project

Find Missing Relations Easily with .missing

It can be kind of clunky to query ActiveRecord for records where the has_manyassociation is empty.

Say I have an Author class that has many Books. One way to query for Authors without books is the following:

class Author < ApplicationRecord
  has_many :books

Author.left_joins(:books).where(books: {id: nil}) 

This totally works, but at least for me is difficult to reason what we're querying. However, Rails 6.1 added a .missing method that really helps clarify what the query is doing:


Much clearer - this will grab all authors that do not have any books.

Docs for further reading. Happy querying!

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.