我最好使用像...这样的陈述。
current_user.workouts.find_by_created_at(Time.now.day)
但这不起作用,我猜是因为时间不匹配。我将继续阅读文档,但我想我会在阅读时发布这个问题以寻求帮助。
谢谢!
的更新 的 使用新的Rails 3支持ARel和命名范围,我将查询重构为...
模型
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
控制器
def create
workouts = current_user.workouts.from_today
.
.
.
end
答案 0 :(得分:5)
如果您使用的是MySQL,则可以执行以下操作:
Rails 3:
current_user.workouts.where('DATE(created_at) = ?', Date.today)
Rails 2:
current_user.workouts.find(:all, :conditions => ['DATE(created_at) = ?', Date.today])
答案 1 :(得分:3)
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])
或
current_user.workouts.find(:all, :conditions => [" created_at between ? AND ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day])
不确定哪个更优化
答案 2 :(得分:3)