Find Missing Relations Easily with .missing
It can be kind of clunky to query ActiveRecord for records where the has_many
association 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
end
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:
Author.where.missing(:books)
Much clearer - this will grab all authors that do not have any books.
Docs for further reading. Happy querying!
Tweet