繁体   English   中英

Rails 3:如何在今天创建的表中查找行?

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

我最好使用像...这样的陈述。

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

如果您使用的是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])
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])

不确定哪个更优化

我为这种操作编写了一个gem,它叫做by_star 有了它,您可以这样做以获取今天创建的所有记录:

current_user.workouts.today

还有很多其他有用的方法。 搏一搏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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