【问题标题】:Best way to do "exclusive OR open-ended" date query in RAILS在 RAILS 中进行“独占式或开放式”日期查询的最佳方式
【发布时间】:2015-01-12 21:41:16
【问题描述】:

坎宁安定律:这必须是完成这项任务的最佳方式。最好的。

# rubies on railz
# Assume we pass an options hash with, possibly, two dates.
# If both dates: do an inclusive between the two
# If start date: do open-ended search
# Else do close-ended search  

def my_date_helper(options)
  start_date = options[:start_date].try(:beginning_of_day)
  end_date   = (options[:end_date] || 6.months.from_now).end_of_day

  if start_date && end_date
    query.where(created_at: start_date..end_date)
  elsif start_date
    query.where("created_at >= ?", start_date)
  else
    query.where("created_at <= ?", end_date)
  end
end

【问题讨论】:

  • 这有问题吗?在事物的宏伟计划中,它似乎是可读的并完成了任务......
  • Nick Veys:感谢您的验证。我们无法想出更优雅的解决方案。有几种写法,但我们发现没有令人信服的理由来改变。我希望我们缺少一些新的 rails helper 或 stdlib 方法。干杯。
  • 不知道query是从哪里来的。

标签: ruby-on-rails ruby date where


【解决方案1】:

你好,我最好的例子:

是 sql 表中的阵营是 TYPE => DATETIME 我正在使用

DATE(created_at) BETWEEN ? and ?,start_date,end_date

为什么?

对于日期时间需要将 created_at 转换为 DATE 类型,如果您比较每个示例 2014-02-10 您需要在 sql 2014-02-10 没有 2014-02-10 14:00:22

如果您需要比较 TYPE DATE TIME

query.where(created_at: start_date..end_date)

问候!

【讨论】:

  • 这并没有解决开放式、封闭式的问题。我们拥有使用已完成的独家“之间”。但是,如果省略了任何一个日期,我们希望该方法能够适当地处理范围。
  • 以最佳方式查询 sql 日期范围
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多