class ActiveRecord::QueryMethods::WhereChain
def missing(*associations)
# LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# SELECT "posts".* FROM "posts"
Post.where.missing(:author, :comments)
that are missing both an author and any comments:
Additionally, multiple relations can be combined. This will return posts
# WHERE "authors"."id" IS NULL
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# SELECT "posts".* FROM "posts"
Post.where.missing(:author)
For example, posts that are missing a related author:
missing relations.
Returns a new relation with left outer joins and where clause to identify
def missing(*associations) associations.each do |association| reflection = scope_association_reflection(association) @scope.left_outer_joins!(association) if @scope.table_name == reflection.table_name @scope.where!(association => { reflection.association_primary_key => nil }) else @scope.where!(reflection.table_name => { reflection.association_primary_key => nil }) end end @scope end