Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How can I find rows in a table that were created today?

Preferably I'd like to use a statement like...

current_user.workouts.find_by_created_at(Time.now.day)

but that doesn't work, I'm guessing because the times don't match up. I'm going to keep reading through the docs, but I thought I'd post this question to seek help while I'm reading.

Thanks!

UPDATE Using the new Rails 3 support for ARel and named scopes, I refactored the query to...

Model

   class Workout < ActiveRecord::Base
      scope :from_today, where(" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)
    .
    .
    .
    end

Controller

def create
  workouts = current_user.workouts.from_today
.
.
.
end
like image 424
BeachRunnerFred Avatar asked Dec 22 '22 15:12

BeachRunnerFred


2 Answers

If you are using MySQL you can do the following:

Rails 3:

current_user.workouts.where('DATE(created_at) = ?', Date.today)

Rails 2:

current_user.workouts.find(:all, :conditions => ['DATE(created_at) = ?', Date.today])
like image 60
Pan Thomakos Avatar answered May 15 '23 02:05

Pan Thomakos


current_user.workouts.find(:all, :conditions => [" YEAR(created_at) = ? AND MONTH(created_at) = ? AND DAY(created_at) = ?", Time.zone.now.year, Time.zone.now.month, Time.zone.now.day])

or

current_user.workouts.find(:all, :conditions => [" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day])

not sure which is more optimized

like image 29
drhenner Avatar answered May 15 '23 02:05

drhenner