Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord - how to fetch records between two dates

Tags:

I have two date columns - from_date and to_date in a database table.

Example:

  • from_date: 2012-09-10
  • to_date: 2012-09-30
  • today: 2012-09-13

I need to fetch all records, if today's date is between from_date and to_date. How do I do that with a SQL query?

If I have loaded the respective record, I can easily decide, if today's date is between from_date and to_date, but I don't know how to fetch those records straight from the database table.

like image 527
user984621 Avatar asked Sep 13 '12 10:09

user984621


2 Answers

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') 
like image 80
Paulo Fidalgo Avatar answered Oct 10 '22 06:10

Paulo Fidalgo


data = ModelName.where("today >= from_date AND today <= to_date") 
like image 28
Salil Avatar answered Oct 10 '22 06:10

Salil