如何在Rails迁移中将列类型更改为间隔?

时间:2016-05-30 16:53:54

标签: postgresql ruby-on-rails-4 migration intervals column-types

我正在使用带有PostGre数据库的Rails 4.2.3。我正在尝试将表格中的列类型更改为“间隔”类型,因此我尝试了此迁移

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

但是在运行“rake db:migrate”时,我得到以下令人失望的错误......

== 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/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract_adapter.rb:472:in `block in log'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activesupport-4.2.5.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `log'

如何更改迁移以使其生效?

2 个答案:

答案 0 :(得分:2)

问题在于Postgres不知道如何将一个整数(我假设现在是 ::cue{ transform: rotateY(180deg); } )转换为一个整数。但您可以使用time_in_ms关键字告诉它。它需要Postgres用来转换所有旧值的表达式。因此,您可以在迁移中使用它:

USING

请注意,如果您这样做,则应编写单独的change_column :my_object_times, :time_in_ms, "interval USING (time_in_ms || ' milliseconds')::interval" up方法,因为这种使用down的方式不会自动可逆。

哦哦:你可以忽略@ Boltz0r的要点。正如@mu所说,它试图解决另一个问题。

答案 1 :(得分: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