使用Postgresql函数进行Rails change_column迁移--将时间改为整数(午夜后的秒数)。

问题描述 投票:0回答:1

桌子 orders 拥有 cuts_off_at 数据类型的列 time without time zone. 这个表和列已经使用了一段时间,因此,这个表有很多保存的记录。我意识到,我希望这一列的数据类型改为 integer 代表 seconds since midnight. 我应该如何格式化change_column这一行?

我尝试了一些不同的方法,但似乎都不对。我相信这是我最接近的尝试。

change_column :orders, :cuts_off_at, 'INTEGER USING EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at))'

它返回的错误是:

syntax error, unexpected tINTEGER, expecting end ...USING EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_...

版本:

postgres版本10.12rails 5.2.4.2。

ruby-on-rails database postgresql database-migration postgresql-10
1个回答
1
投票

两种迁移方法并不具有破坏性,而且会让你在一个直接的更新语句中使用postgres的魔法。它还会让你确保一切都能按照预期工作......

  def change
    rename_column :orders, :cuts_off_at, :cuts_off_at_old
    add_column :orders, :cuts_off_at, :integer
    execute("UPDATE orders SET cuts_off_at = EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at_old))")
  end

然后,你可以简单地在以后的迁移中删除旧列... ...

 def change
    remove_column :orders, :cuts_off_at_old
 end

或者如果你需要一个向上向下的... ...

  def up
    rename_column :orders, :cuts_off_at, :cuts_off_at_old
    add_column :orders, :cuts_off_at, :integer
    execute("UPDATE orders SET cuts_off_at = EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at_old))")
  end

  def down
    remove_column :orders, :cuts_off_at
    rename_column :orders, :cuts_off_at_old, :cuts_off_at
  end
© www.soinside.com 2019 - 2024. All rights reserved.