Finding missing/associated records in Rails
Rails has some built in methods to help you find records which may have missing associated records.
For example, let’s assume we have an app where an Invoice
has many Payment
s, and we wanted to find all invoices which have no payments:
Invoice.where.missing(:payments)
We’ll get back a collection of all invoices which have no payments.
Much cleaner than writing messy joins!
Also, on the flip side you can find all invoices with payments like this:
Invoice.where.associated(:payments)