Method: ActiveRecord::QueryMethods::WhereChain#missing
- Defined in:
- lib/active_record/relation/query_methods.rb
#missing(*args) ⇒ Object
Returns a new relation with left outer joins and where clause to identify missing relations.
For example, posts that are missing a related author:
Post.where.missing(:author)
# SELECT "posts".* FROM "posts"
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# WHERE "authors"."id" IS NULL
Additionally, multiple relations can be combined. This will return posts that are missing both an author and any comments:
Post.where.missing(:author, :comments)
# SELECT "posts".* FROM "posts"
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
# WHERE "authors"."id" IS NULL AND "comments"."id" IS NULL
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/active_record/relation/query_methods.rb', line 71 def missing(*args) args.each do |arg| reflection = @scope.klass._reflect_on_association(arg) opts = { reflection.table_name => { reflection.association_primary_key => nil } } @scope.left_outer_joins!(arg) @scope.where!(opts) end @scope end |