Reputation: 18558
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
Upvotes: 4
Views: 4299
Reputation: 107718
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.
Upvotes: 3
Reputation: 34340
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])
Upvotes: 5
Reputation: 2230
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
Upvotes: 3