簡體   English   中英

如何在Postgres中獲得MIN才能與Rails完美搭配?

[英]How do I get MIN in Postgres to play nice with Rails?

現在,我在Rails中運行着一個龐大的查詢:

@foo_collection = Foo.select('
    foos.id,
    array_agg() AS some_aggregate, -- about 20 of these, but they're not the problem
    MIN(bars.some_date), -- Returning wrong type - this is the problem
').joins('
    INNER JOIN bars... -- A LOT of joins - but also not the problem
').where('
    some_conditions
').group('
    foos.id
')

該查詢根據PGAdmin提取我想要的數據。 沒有做的就是很好地轉換成Rails。 嘗試將@foo_collection.some_dateDateTime對象以創建時差,結果是:

undefined method `-' for "2014-04-01 16:12:35.461712":String

有什么辦法哄我的PG輸出為Rails提供DateTime而不是String ,還是我必須告訴Rails將所有some_date s解析為String

到目前為止,我已經有Rails的轉換處理,所有這@foo_collection.some_date小號to_datetime ,然后to_f這樣我就可以找到它們之間的時間間隔。 但這有很大的開銷-如果我可以直接從數據庫中撤回一個datetime對象,那會容易得多。

Rails最有可能將字段拉為字符串,因為您不是在查詢具有定義的列類型的模型,我認為最好的選擇是將查詢更改為輸出到表,然后使用Rails模型查詢該表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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