instance method
associated
Ruby on Rails 8.0.4
Since v7.0.10Signature
associated(*associations)
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
Parameters
-
associationsrest
Source
# File activerecord/lib/active_record/relation/query_methods.rb, line 88
def associated(*associations)
associations.each do |association|
reflection = scope_association_reflection(association)
unless @scope.joins_values.include?(reflection.name) || @scope.left_outer_joins_values.include?(reflection.name)
@scope.joins!(association)
end
association_conditions = Array(reflection.association_primary_key).index_with(nil)
if reflection.options[:class_name]
self.not(association => association_conditions)
else
self.not(reflection.table_name => association_conditions)
end
end
@scope
end
Defined in activerecord/lib/active_record/relation/query_methods.rb line 88
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::QueryMethods::WhereChain