How to query records which has missing associations in Rails 6


Rails 6 provides a simpler way to query the records which does not have any associated records or orphan records so to say.

How to query records with No associations in Rails

This reads, Fetch all the users which have no posts.

  User.left_outer_joins(:posts).where(posts: { user_id: nil })

Fetch Records with missing associations Rails 6

It is as easy as using missing with Rails 6

  # => Gonna give out same results as previous query

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...