2015-09-28 149 views
0

在Rails 3的應用程序,我有表subscription_schedules,其中有「時間」類型的列更改「時間」列「日期時間」

例如記錄lokks這樣的:

#<Subscription::Schedule id: 3504, subscription_id: 4961, scheduled_at: "2000-01-01 01:11:00", primary: true, created_at: "2015-09-28 01:13:34", updated_at: "2015-09-28 01:13:34", active: true> 

什麼我想要做的是將scheduled_at轉換爲datetime。我決定添加新列'temp_scheduled_at',將所有'scheduled_at'保存到它,使用change_column()方法將'scheduled_at'更改爲datetime,並稍後將'temp_scheduled_at'中的內容移動到'scheduled_at'

它看起來像這樣:

add_column :subscription_schedules, :temp_scheduled_at, :datetime 
Subscription::Schedule.select {|s| s.subscription}.each do |schedule| 
     schedule.temp_scheduled_at = schedule.scheduled_at 
     schedule.scheduled_at = nil 
     begin 
      schedule.save! 
     rescue => e 
     puts schedule.id 
     end 
    end 

change_column :subscription_schedules, :scheduled_at, :datetime 

遺憾的是,多數民衆贊成在那裏的煩惱開始。後來打電話Subscription::Scheudule.all後,我得到

Invalid date in field 'scheduled_at': 2001-00-00 00:00:00 

我真的不知道是什麼原因造成這個錯誤,更改列類型的記錄與「無效的日期」之前是這樣的:

#<Subscription::Schedule id: 2555, subscription_id: 4102, scheduled_at: "2000-01-01 05:00:00", primary: true, created_at: "2015-06-23 16:12:01", updated_at: "2015-06-23 16:12:01", active: true> 
+0

scheduled_at列已經包含datetime值。你可以發佈當前的輸出和期望的輸出 –

+0

它看起來像它,但在MySQL中它是列'時間',也在軌道上只有幾小時,分鐘和秒存儲。目前的輸出看起來像上面,我想要的是日期時間列,我後來填寫的信息 – Leo

+0

你想要任何虛擬日期與那個時間相關聯? –

回答

0

我建議你在mysql查詢中使用它。您可以在mysql查詢中更改日期時間,並將其引用爲新的列名稱。與編程方式相比非常簡單。爲前

select schedule_at, now() as temp_scheduled_at from tablename; 

你可以閱讀更多的日期時間函數here