instance method
associated
Ruby on Rails 7.0.10
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
Parameters
-
associationsrest
Source
# File activerecord/lib/active_record/relation/query_methods.rb, line 76
def associated(*associations)
associations.each do |association|
reflection = scope_association_reflection(association)
@scope.joins!(association)
if reflection.options[:class_name]
self.not(association => { reflection.association_primary_key => nil })
else
self.not(reflection.table_name => { reflection.association_primary_key => nil })
end
end
@scope
end
Defined in activerecord/lib/active_record/relation/query_methods.rb line 76
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::QueryMethods::WhereChain