##TIL 🇬🇧
How to query nil or not nil associations with ruby on rails
Jeanro Krupa
![](https://www.ruby-on-rails-jobs.com/rails/active_storage/representations/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBaVVCIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--020dc5197a2803cb2f242e33df451a0318997e56/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdCem9MWm05eWJXRjBTU0lJYW5CbkJqb0dSVlE2RW5KbGMybDZaVjkwYjE5bWFYUmJCMmsxYVRVPSIsImV4cCI6bnVsbCwicHVyIjoidmFyaWF0aW9uIn19--4e53a6157c2fc9d37b3549e5e00257a180535e2e/jeanro_ruby_on_rails_jobs.jpg?locale=en)
Jeanro Krupa
1 min read
![](https://www.ruby-on-rails-jobs.com/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBZDg9IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--4b355b17c0fa5fd2644ad5516bbf5771ee62f901/til_about_query_in_rails.png?locale=en)
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