Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rails where condition with OR is NULL inside

I want to get all the records where disbursed at is either NULL or within a timeframe. How can I add a or where disbursed_at IS NULL to the condition inside the where?
My actual query is way longer, I wouldn’t want to repeat it all using .or

Investor.left_join(:disbursements).where(disbursements: { disbursed_at: year_period })

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Generally speaking you can add an OR column_X IS NULL condition by providing an Array, containing at least one nil element, as part of the Hash arguments.

For Example:

Investor
  .left_join(:disbursements)
  .where(disbursements: { disbursed_at: [year_period,nil] })

Assuming year_period is a Range this should result in

SELECT 
  investors.* 
FROM 
  investors 
  LEFT OUTER JOIN disbursements ON disbursements.investor_id = investors.id
WHERE 
  disbursements.disbursed_at BETWEEN xxxxx AND xxxxx 
  OR disbursements.disbursed_at IS NULL 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading