简体   繁体   中英

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

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])
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

I wrote a gem for this kind of operation, it's called by_star . With it, you could do this to get all records created today:

current_user.workouts.today

There's plenty of other helpful methods too. Give it a go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM