Method: ActiveRecord::QueryMethods::WhereChain#missing

Defined in:
activerecord/lib/active_record/relation/query_methods.rb

#missing(*associations) ⇒ 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


124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'activerecord/lib/active_record/relation/query_methods.rb', line 124

def missing(*associations)
  associations.each do |association|
    reflection = scope_association_reflection(association)
    @scope.left_outer_joins!(association)
    association_conditions = Array(reflection.association_primary_key).index_with(nil)
    if reflection.options[:class_name]
      @scope.where!(association => association_conditions)
    else
      @scope.where!(reflection.table_name => association_conditions)
    end
  end

  @scope
end