2012-05-19 25 views
1

我有一個名爲subs的表,其中有許多articlesarticles表具有名爲published的時間戳列。來自連接表的時間戳列成爲字符串

Sub.select("subs.*,MAX(articles.published) published").joins("LEFT OUTER JOIN articles ON subs.id=articles.sub_id").group("subs.id").first.published.class 
=> String 
Article.select("max(published) published").group("id").first.published.class 
=> ActiveSupport::TimeWithZone 

我想從第一個查詢中得到一個ActiveSupport::TimeWithZone對象。

+0

有沒有想過如何處理這個?我現在遇到同樣的問題...... – kafuchau

+0

不,我用一個額外的查詢語句來獲取時間戳列 – peon

回答

0

導軌3

滑軌確定如何基於他們的數據庫列定義爲類型鑄造屬性。例如,假設您的Sub型號上有created_at方法。加載記錄時使用read_attributeActiveRecord::AttributeMethods::Read)。這使用type_cast_attribute,它根據列信息確定如何投射值。例如,如果你正在使用PostgreSQL,它可以使用:

Sub.columns.detect { |c| c.name == "created_at" }.type_cast_code("v") 
=> "ActiveRecord::ConnectionAdapters::PostgreSQLColumn.string_to_time(v)" 

但Rails不知道如何處理那些不上Sub模型列做。所以它只是給出一個String。如果你需要一個ActiveSupport::TimeWithZone對象的工作,你可以投的價值:

published = Sub.select("subs.*,MAX(articles.published) published").joins("LEFT OUTER JOIN articles ON subs.id=articles.sub_id").group("subs.id").first.published 
published.present? ? Time.zone.parse(published) : nil 

軌道4

在Rails 4,Rails是關於這種類型轉換的聰明。執行SQL時,將創建ActiveRecord::Result,並將column_types傳遞給初始值設定項。在您的示例Sub.select查詢中,published列將轉換爲Time對象。

相關問題