0

I am running a SQL query which returns some orders each having a date. I want to check which orders were made on current date ?

I am able to do so by:

orders = Order.find_by_sql(query).reject {|o|
  today = Time.now
  end_of_today = Time.local(today.year, today.month, today.day, 23, 59, 59)
  start_of_today = Time.local(today.year, today.month, today.day, 00,00,00 )
  o.date > end_of_today
  o.date < start_of_today
}.sort_by {|o|
  o.delivery_date
}

'orders' contain all the orders which were made at any time Today.

Is there a simpler way of doing this in ruby ?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Mandar
  • 287
  • 1
  • 3
  • 4
  • You should check out this question: http://stackoverflow.com/questions/14404175/query-where-date-date-today-with-rails-mysql-and-active-record – Vincent Jan 28 '16 at 19:44

4 Answers4

1

To get the orders made on the current date, you can do the following:

orders = Order.where("date >= ?", Time.zone.now.beginning_of_day).order(:delivery_date)

Hope this helps!

Zoran
  • 4,196
  • 2
  • 22
  • 33
0

use DateTime.now.beginning_of_day

Order.where('date >= ?', DateTime.now.beginning_of_day).order(:delivery_date)
Oleh Sobchuk
  • 3,612
  • 2
  • 25
  • 41
  • `Time.current` or `Time.zone.now` are preferred, so they use the application's timezone, rather than the computer's timezone. – Leonel Galán Jan 28 '16 at 19:55
0

Now you are getting all the orders from the database (depends on what string is in the query) and then filtering the array, which is not the most efficient way if you have a large database. Much better way is doing this on SQL side.

Just use pure string conditions:

# Or set it to any other date in the past
target_date = Time.zone.now 

orders = Order.find_by_sql(query)
.where("date >= ?", target_date.beginning_of_day)
.where("date <= ?", target_date.end_of_day)
.order(:delivery_date)

More details here: http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions

More info on Active Support DateTime methods: http://api.rubyonrails.org/classes/DateTime.html#method-i-beginning_of_day

Konstantine Kalbazov
  • 2,643
  • 26
  • 29
0

I think you are looking for this, it will cover all orders for today

orders = Order.where("created_at <= ? AND created_at >= ?", Time.zone.now.end_of_day, Time.zone.now.beginning_of_day).order(:delivery_date)
Tushar Maroo
  • 325
  • 1
  • 5
  • 24