##TIL ๐ฌ๐ง
How to query nil or not nil associations with ruby on rails
Jeanro Krupa
Jeanro Krupa
1 min read
Thanks to my amazing friend Today I learn how how to nicely query nil or not nil associations with ruby on rails +6.1
It's an exemple from this website where I have a Company model that has_many jobs. I need to be able to find all the companies with a job attach and all the companies without.
It's an exemple from this website where I have a Company model that has_many jobs. I need to be able to find all the companies with a job attach and all the companies without.
class Account < ApplicationRecord has_many :jobs scope :with_a_job, -> { where.associated(:jobs) } scope :without_a_job, -> { where.missing(:jobs)} end
The resulting SQL is:
for missing:ย
SELECT "accounts".* FROM "accounts" LEFT OUTER JOIN "jobs" ON "jobs"."account_id" = "accounts"."id" WHERE "jobs"."id" IS NULL
fir associated:
SELECT "accounts".* FROM "accounts" INNER JOIN "jobs" ON "jobs"."account_id" = "accounts"."id" WHERE "jobs"."id" IS NOT NULL