如何在 Heroku 中更改列类型? [英] How do I change column type in Heroku?

查看:25
本文介绍了如何在 Heroku 中更改列类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 db:migrations 放入我的 heorku 实例中,但出现错误.常见问题解答将我的错误描述如下:

I am trying to rake the db:migrations into my heorku instance and I get an error. The FAQ described my error as below:

无法更改列类型

示例:PGError:错误:列verified_at"不能强制转换为类型约会"

Example: PGError: ERROR: column "verified_at" cannot be cast to type "date"

原因:PostgreSQL 不知道如何将该表中的所有行强制转换为指定类型.最有可能的意思你有一个整数或一个字符串那个专栏.

Cause: PostgreSQL doesn’t know how to cast all the rows in that table to the specified type. Most likely it means you have an integer or a string in that column.

解决方案:检查您的记录并确保它们可以转换为新型.有时更容易只是避免使用change_column,重命名/创建新列相反.

Solution: Inspect your records and make sure they can be converted to the new type. Sometimes it’s easier to just avoid using change_column, renaming/creating a new column instead.

我现在如何更改此迁移.这是我遇到的问题.对于我的联系人表,我创建了以下内容:

How do I change this migration now. This is the problem that I have. For my Contacts table, I created the following:

  t.string :date_entered

在以后的迁移中,我执行以下操作:

In a later migration, I do the following:

 change_column :contacts, :date_entered, :date

这个 change_column 似乎是问题所在.

This change_column appears to be the problem.

我应该...手动更改迁移吗?有没有办法清理我的表中的数据(我不知道 Heroku 会识别表中的数据,因为我在做耙子).

Should I...change by hand that migration? Is there a way I can clean the data in my tables (I didn't know Heroku would recognize the data in the table because I'm doing a rake).

我显然需要更改这个值,它在我的整个应用程序中使用.谢谢.

I obviously need to change this value and it is used throughout my application. Thanks.

这就是我正在尝试的...想法?

def self.up
  #change_column :contacts, :date_entered, :date
  #this fails in postgres, so trying the same outcome 

  rename_column :contacts, :date_entered, :date_entered_old
  add_column :contacts, :date_entered, :date
  remove_column :contacts, :date_entered_old
end

def self.down
  add_column :contacts, :date_entered_old
  remove_column :contacts, :date_entered
  rename_column :contacts, :date_entered_old, :date_entered
end

推荐答案

执行以下操作:

  1. 重命名A列
  2. 创建新的 B 列作为日期
  3. 将数据从 A 移动到 B
  4. 删除A

换句话说

def self.up
  rename_column :contacts, :date_entered, :date_entered_string
  add_column :contacts, :date_entered, :date

  Contact.reset_column_information
  Contact.find_each { |c| c.update_attribute(:date_entered, c.date_entered_string) } 
  remove_column :contacts, :date_entered_string
end

这篇关于如何在 Heroku 中更改列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆