簡體   English   中英

如何在Rails查詢的WHERE子句中編寫DateTime.current?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM