Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date range query in ruby/rails

I am trying to run the following query. I know the syntax is wrong, but I can't quite figure out what is wrong with it. Basically, I am trying to find how many games have dates that are within 45 days of today. I have a model called Game that has a field attribute called date_of_game. My query:

Game.where(date_of_game: <= (Time.now + 45.days)).count

Thanks!!

like image 213
Trung Tran Avatar asked Jun 04 '14 16:06

Trung Tran


1 Answers

You said:

how many games have dates that are within 45 days of today

But your code will retrieve all the games having a date less than Today + 45 days, which means it would return Game of last year, for example. To follow your statement, you should use:

Game.where(date_of_game: Date.current..(Date.current + 45.days))

This code will return all games coming out in the next 45 days.


What is .. ?

It is the operator to create Ranges. Try in your console:

> (1..5).each do |some_number|
>   puts some_number
> end
1
2
3                                                                                                                                                                                                                                                                              
4                                                                                                                                                                                                                                                                              
5                                                                                                                                                                                                                                                                              
 => 1..5   

It also works with dates:

> (Date.today..(Date.today+5.days)).each do |some_date|
>   puts some_date                                                                                                                                                                                                                                            
> end                                                                                                                                                                                                                                                         
2014-06-04
2014-06-05
2014-06-06
2014-06-07
2014-06-08
2014-06-09
 => Wed, 04 Jun 2014..Mon, 09 Jun 2014 
like image 116
MrYoshiji Avatar answered Sep 30 '22 12:09

MrYoshiji