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