ruby on rails中有一个应用
模式.rb
ActiveRecord::Schema.define(version: 20170302072830) do
create_table "stocks", force: :cascade do |t|
t.string "name", null: false
t.integer "unit_price", null: false
t.integer "interest", null: false
t.integer "duration", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.index ["user_id"], name: "index_stocks_on_user_id", using: :btree
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "username", default: "", null: false
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
end
end
开发过程中有几次迁移
迁移到 Heroku heroku rake db:migrate
我得到一个日志
持续时间字段及其整数类型如何?类型从日期更改为整数。
ALTER TABLE "stocks" ALTER COLUMN "duration" TYPE integer PG::DatatypeMismatch: ERROR: column "duration" cannot be cast automatically to type integer
好吧,他的暗示并没有告诉我任何事情。
提示:您可能需要指定“USING duration::integer”。
您的类型更改可能会导致数据丢失。PostgreSQL只隐式地做那些不会导致损失的转换,但是你传递给一个更“窄”的类型,所以你必须明确指定如何转换现有的值。这是一种预防措施,因此您不会轻弹一下手腕就毁掉自己的数据。
Postgres 甚至向您建议如何在 postgres 语言级别修复列更改命令,您只需将此建议翻译成 railmigration 语法:
可能是由于在不同的迁移中相同的字段我有不同的数据类型,所以发生了这个错误。
新的迁移不改变字段类型,而是删除它并创建一个新的是正确的。
在我的例子中,我完全删除了旧的迁移,创建了一个新的迁移,我在其中指出所有表都已经正确的数据,这解决了问题。