【问题标题】:Rails ActiveRecord Find with DateRails ActiveRecord 查找日期
【发布时间】:2011-01-28 21:01:04
【问题描述】:

我很难弄清楚这一点,但我如何告诉我的 finder 语句忽略数据库中 Datetime 字段的时间?

def trips_leaving_in_two_weeks
  Trip.find(:all, :conditions => ["depart_date = ?", 2.weeks.from_now.to_date])
end

我希望离开日期仅作为日期返回,但它也会不断返回时间并导致这种相等性不起作用。有什么方法可以与日期进行比较吗?谢谢

编辑

这是我现在使用的有效代码:

Trip.find(:all, :conditions => ["DATE(depart_date) = ?", 2.weeks.from_now.to_date])

【问题讨论】:

  • depart_date 是日期还是日期时间?

标签: sql ruby-on-rails activerecord


【解决方案1】:

不确定您使用的是哪个数据库,但这是否有效?

"depart_date = DATE(?)"

【讨论】:

  • 不,它仍然没有返回任何内容。 2.weeks.from_now.to_date 很好地通过了,只是比较中的depart_date 作为日期时间返回。所以现在它正在将日期与日期时间对象进行比较。不过谢谢
  • 实际上,我将 DATE() 方法切换到了 depart_date 并且有效!你得到了让我走上正确道路的公认答案。 :) 谢谢
  • 换个方式试试:"DATE(depart_date) = ?", 2.weeks.from_now.to_date 它应该可以工作。
【解决方案2】:

我会使用这种方法:

Rails 3.x

Trip.where(
  :depart_date => 2.weeks.from_now.beginning_of_day..2.weeks.from_now.end_of_day
)

Rails 2.x

Trip.all(
:conditions => {
  :depart_date => 2.weeks.from_now.beginning_of_day..2.weeks.from_now.end_of_day
})

如果您为depart_date 列编制索引,此解决方案将非常有效,因为查询使用了索引。此解决方案是 DB 中立的。

在 where 子句中使用计算字段时,性能会下降(除非有特殊索引)。

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2011-01-23
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多