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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With