3

我使用Rails 4.2.3和PostGre db。我想在我的表中的列類型更改爲「間隔」的類型,所以我想這個遷移如何在我的Rails遷移中將列類型更改爲間隔?

class ChangeTimeInMsInMyObjectTimes < ActiveRecord::Migration 
    def change 
    change_column :my_object_times, :time_in_ms, :interval 
    end 
end 

但一旦運行「耙分貝:遷移,」我得到了以下令人失望的錯誤...

== 20160530164019 ChangeTimeInMsInMyObjectTimes: migrating ======================== 
-- change_column(:my_object_times, :time_in_ms, :interval) 
rake aborted! 
StandardError: An error has occurred, this and all later migrations canceled: 

PG::DatatypeMismatch: ERROR: column "time_in_ms" cannot be cast automatically to type interval 
HINT: You might need to specify "USING time_in_ms::interval". 
: ALTER TABLE "my_object_times" ALTER COLUMN "time_in_ms" TYPE interval 
/Users/davea/.rvm/gems/[email protected]/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec' 
/Users/davea/.rvm/gems/[email protected]/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute' 
/Users/davea/.rvm/gems/[email protected]/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract_adapter.rb:472:in `block in log' 
/Users/davea/.rvm/gems/[email protected]/gems/activesupport-4.2.5.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument' 
/Users/davea/.rvm/gems/[email protected]/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `log' 

如何更改我的遷移以使其工作?

+0

https://gist.github.com/clarkdave/6529610 – Boltz0r

+0

除了把HTA tfile在配置/初始化,是我需要有其他的配置?我詢問是因爲在使用此文件並運行「rake db:migrate」時,出現錯誤「NameError:未定義方法'simplified_type'用於類'ActiveRecord :: ConnectionAdapters :: PostgreSQLColumn'」。 – Dave

+1

這個要點是試圖解決錯誤的問題,你已經有''interval'類型的ActiveRecord支持,你的問題是在錯誤消息(列「time_in_ms」不能自動轉換爲類型間隔)作爲解決方案(添加一個適當的USING子句)。 –

回答

1

問題是,Postgres不知道如何投射一個整數(我認爲這就是time_in_ms現在)。但你可以用USING關鍵字來告訴它。它需要一個Postgres將用來轉換所有舊值的表達式。如果你這樣做,你應該寫單獨updown方法,因爲使用change_column的這種方式是不可逆的自動

change_column :my_object_times, :time_in_ms, 
       "interval USING (time_in_ms || ' milliseconds')::interval" 

注:所以,你可以在你的遷移使用。

哦另外:你可以忽略@ Boltz0r的要點。正如@mu所說,它正試圖解決一個不同的問題。

0

嘗試

class ChangeTimeInMsInMyObjectTimes < ActiveRecord::Migration 
    def change 
    remove_column :my_object_times, :time_in_ms, :your_current_type 
    add_column :my_object_times, :time_in_ms, :interval 
    end 
end 
相關問題