1

I'm trying to get books ActiveRecord objects that have a 'from or 'to' between a date range (start_date..end_date).

This code works just fine:

Book.where(from: start_date..end_date)

But I want to use 'or' in my statement and this code fails:

Book.where("from: ? OR to: ?", (start_date..end_date), (start_date..end_date))

Please help me to find my mistake.

Nadiya
  • 1,421
  • 4
  • 19
  • 34

3 Answers3

1

You can try this -

Book.where("books.from BETWEEN ? AND ? OR books.to BETWEEN ? AND ?", start_date,end_date,start_date,end_date)
dp7
  • 6,651
  • 1
  • 18
  • 37
  • It is almost right. I get SELECT `books`.* FROM `books` WHERE (from BETWEEN '2016-02-01' AND '2016-02-29' OR to BETWEEN '2016-02-01' AND '2016-02-29'). But a little part is still missing (should be `books`.`from` BETWEEN ... AND ...) – Nadiya Apr 05 '16 at 07:52
1

Check the Rails guides on Range conditions:

Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)

That will produce the following SQL:

SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')

So given in you can use or in ActiveRecord in the Rails 5, you can do

Book.where(from: start_date..end_date).or(Book.where(from: new_start_date..new_end_date))

Notes: You don't need to use rails 5 to use this OR query. We can also used it with rails 4.2, thanks to gem where-or

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115
0
 if from < to
    Book.where("from >= #{start_date} OR to  <= #{end_date}")
 else 
  // do something else
 end
z.shan
  • 341
  • 1
  • 2
  • 13