![](/img/trans.png)
[英]Ruby on Rails - Handling of DateTime.current and User Input Time
[英]How to write DateTime.current in WHERE clause of Rails query?
在我的模型之一,我有一个名为列开始这是一个DateTime,我希望能够写一个类的方法,将返回其区别记录DateTime.current
并开始列比N秒更大。
这是我到目前为止的内容:
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
理想情况下,这应该与数据库引擎无关,即使现在我正在使用PostgreSQL。
您应该使用范围并像这样写
scope :started, where('started IS NOT NULL')
scope :elapsed_since, Proc.new {|sec| where("NOW() - started > ?", sec.seconds)}
这样使用
model.started.elapsed_since(10)
编辑
MySQL的
mysql>选择NOW()-10;
+ ----------------------- +
| NOW()-10 |
+ ----------------------- +
| 20140707200211.000000 |
+ ----------------------- +
mysql>选择NOW()-“ 10”;
+ ---------------- +
| NOW()-“ 10” |
+ ---------------- +
| 20140707200223 |
+ ---------------- +
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.