Reputation: 1527
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.
Upvotes: 1
Views: 50
Reputation: 22296
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
Upvotes: 1
Reputation: 6749
You can try this -
Book.where("books.from BETWEEN ? AND ? OR books.to BETWEEN ? AND ?", start_date,end_date,start_date,end_date)
Upvotes: 1
Reputation: 339
if from < to
Book.where("from >= #{start_date} OR to <= #{end_date}")
else
// do something else
end
Upvotes: 0