method

associated

associated(*associations)
public

Returns a new relation with joins and where clause to identify associated relations.

For example, posts that are associated to a related author:

Post.where.associated(:author)
# SELECT "posts".* FROM "posts"
# INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# WHERE "authors"."id" IS NOT NULL

Additionally, multiple relations can be combined. This will return posts associated to both an author and any comments:

Post.where.associated(:author, :comments)
# SELECT "posts".* FROM "posts"
# INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
# WHERE "authors"."id" IS NOT NULL AND "comments"."id" IS NOT NULL

You can define join type in the scope and associated will not use `JOIN` by default.

 Post.left_joins(:author).where.associated(:author)
 # SELECT "posts".* FROM "posts"
 # LEFT OUTER JOIN "authors" "authors"."id" = "posts"."author_id"
 # WHERE "authors"."id" IS NOT NULL

 Post.left_joins(:comments).where.associated(:author)
 # SELECT "posts".* FROM "posts"
 # INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
 # LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
#  WHERE "author"."id" IS NOT NULL