Rails 7 - 'associated' query method to check association presence
What
Rails 7 provides a query method associated
to return list of objects which have association presence.
Read more: Add where.associated to check association presence
Example
class Category < ApplicationRecord
has_many :posts
end
class Post < ApplicationRecord
belongs_to :category
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
end
Before Rails 7
When we search all posts, which refer an active category, we use this query:
[1] pry(main)> Post.joins(:category).where.not(category: {id: nil})
Post Load (0.2ms) SELECT "posts".* FROM "posts"
INNER JOIN "categories" ON "categories"."id" = "posts"."category_id"
WHERE "categories"."id" IS NOT NULL
(Note that: We should not use Post.where.not(category_id: nil)
cause category can be deleted, but post.category_id
is still present)
Rails 7
[1] pry(main)> Post.where.associated(:category)
SELECT "posts".* FROM "posts"
INNER JOIN "categories" ON "categories"."id" = "posts"."category_id"
WHERE "categories"."id" IS NOT NULL
[2] pry(main)> Post.where.associated(:category, :comments)
SELECT "posts".* FROM "posts"
INNER JOIN "categories" ON "categories"."id" = "posts"."category_id"
INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
WHERE "categories"."id" IS NOT NULL AND "comments"."id" IS NOT NULL