简体   繁体   English

如何在Rails查询的WHERE子句中编写DateTime.current?

[英]How to write DateTime.current in WHERE clause of Rails query?

In one of my models I have a column called started which is a DateTime, and I want to be able to write a class method that would return the records which difference between DateTime.current and started column is bigger than N seconds. 在我的模型之一,我有一个名为列开始这是一个DateTime,我希望能够写一个类的方法,将返回其区别记录DateTime.current开始列比N秒更大。

Here is what I have so far: 这是我到目前为止的内容:

def self.elapsed_started_bigger_than(sec = 10)
  where('started IS NOT NULL').
  where( ((DateTime.current - started) * 24 * 60 * 60).to_i > sec) # This is what I don't know how to write
end

Ideally this should be database engine agnostic, even though right now I am using PostgreSQL. 理想情况下,这应该与数据库引擎无关,即使现在我正在使用PostgreSQL。

You should use a scope and write it like this 您应该使用范围并像这样写

scope :started, where('started IS NOT NULL')

scope :elapsed_since, Proc.new {|sec| where("NOW() - started > ?", sec.seconds)}

Use it like this 这样使用

model.started.elapsed_since(10)

EDIT 编辑

Mysql MySQL的

` mysql> select NOW() - 10; mysql>选择NOW()-10;

+-----------------------+ + ----------------------- +

| | NOW() - 10 | NOW()-10 |

+-----------------------+ + ----------------------- +

| | 20140707200211.000000 | 20140707200211.000000 |

+-----------------------+ + ----------------------- +

mysql> select NOW() - "10"; mysql>选择NOW()-“ 10”;

+----------------+ + ---------------- +

| | NOW() - "10" | NOW()-“ 10” |

+----------------+ + ---------------- +

| | 20140707200223 | 20140707200223 |

+----------------+ + ---------------- +

` `

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

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