thisfeller
thisfeller

Reputation: 798

Rails Active Record query -- 'or' conditions

I have a jobs table; each job has a start_date and an end_date. For a given month I want to pull all jobs that were "running" in any part of, or all of some month. The problem is how to write the query for the 5 different "or" conditions needed to capture the notion of a job running in all of or any part of the month. So, I need all jobs that started before the beginning of the month and ended during the month OR all jobs that started and ended during the month OR all jobs that started in the month and finished after the end of the month... Well, there is three of the five. So in the Jobs.where clause, how is the "or" compactly expressed?

Upvotes: 1

Views: 458

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

beginning_of_month = Time.now.beginning_of_month
end_of_month = Time.now.end_of_month
Job.where("(start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?)", beginning_of_month, end_of_month, beginning_of_month, end_of_month)

Using standard ActiveRecord I don't think we can go much shorter. Without the OR, the BETWEEN can be expressed elegantly this way :

Job.where(start_date: beginning_of_month..end_of_month)

But since you need the OR, can't think of anything better, but you may be interested in looking at the squeel gem

Upvotes: 3

Related Questions