【问题标题】:check current time exists between model attributes检查模型属性之间是否存在当前时间
【发布时间】:2019-10-17 11:03:08
【问题描述】:

来自名为 VehicleSchedule 的模型,具有两个 datetime 属性 start_time 和 end_time。我应该如何获取给定时间安排的车辆数量?

类似下面的东西

VehicleSchedule.where('start_time >= ? and end_time <= ?', Time.current, Time.current).count

【问题讨论】:

  • 您当前的实现有什么问题?据我从你的描述中可以看出,这非常好。唯一非常小的改进是删除重复:Vehicle.where('start_time &gt;= :time and end_time &lt;= :time', time: Time.current).count
  • @TomLord start_time: 17/10/2019 04:00 end_time: 17/10/2019 05:00 和 current_time: 17/10/2019 04:30 这会失败吗?
  • 哦,等等... &gt;= 和 &lt;= 运算符倒数。就是这样。
  • 顺便说一句,你的文字说VehicleSchedule,但代码使用Vehicle。请解决这个问题,或者——如果实际上有两个模型——澄清它们是如何相互关联的。

标签: mysql ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

&lt;= 和 &gt;= 运算符倒数。

此外,您可以通过使用相同的占位符引用两个值来删除重复项:

Vehicle
  .joins(:vehicle_schedules)
  .where('vehicle_schedules.start_time <= :time AND vehicle_schedules.end_time >= :time', time: Time.current)
  .count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多