我正在尝试创建一个范围,其中添加了 checkin_time (DateTime),持续时间 (Int) 以小时为单位,大于或等于 Time.now
像这样
scope :current, -> { where('checkin_time + duration.hours >= ?', Time.now) }
但是,上面的字符串 'checkin_time + duration.hours >= ?'
无效。我怎样才能获得正确的结果?
最佳答案
使用 PostgreSQL 最简单的事情是将 duration
转换为 interval
并将该 interval
添加到时间戳中。像这样:
where("checkin_time + (duration || 'hours')::interval >= ?", Time.now)
甚至:
where("checkin_time + (duration || 'hours')::interval >= now()")
持续时间|| 'hours'
构建一个类似于 '6hours'
的字符串,然后 ::interval
将该字符串转换为一个 interval
,它可以是添加到时间戳。
关于ruby-on-rails - 具有组合属性的 Rails 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41839393/