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.
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.
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> select NOW() - 10;
+-----------------------+
| NOW() - 10 |
+-----------------------+
| 20140707200211.000000 |
+-----------------------+
mysql> select NOW() - "10";
+----------------+
| NOW() - "10" |
+----------------+
| 20140707200223 |
+----------------+
`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.