Rails Migrations:试图将字符串的类型从字符串更改为整数 [英] Rails Migrations: tried to change the type of column from string to integer

查看:280
本文介绍了Rails Migrations:试图将字符串的类型从字符串更改为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rails应用程序中使用rails generate migrations命令创建了一个表。这是迁移文件:

I created a table in my rails app with rails generate migrations command. Here is that migration file:

class CreateListings < ActiveRecord::Migration
  def change
    create_table :listings do |t|
      t.string :name
      t.string :telephone
      t.string :latitude
      t.string :longitude

      t.timestamps
    end
  end
end

然后我想存储纬度和经度作为整数所以
我试图运行:

Then I wanted to store the latitude and longitude as integers so I tried to run:

rails generate migration changeColumnType

,该文件的内容为:

class ChangeColumnType < ActiveRecord::Migration
  def up
    #change latitude columntype from string to integertype
    change_column :listings, :latitude, :integer
    change_column :listings, :longitude, :integer
    #change longitude columntype from string to integer type
  end

  def down  
  end
end

我期望列类型更改,但rake已中止,并显示以下错误消息。我想知道为什么这没有经历?我在我的应用程序中使用postgresql。

I was expecting the column type to change however the rake was aborted and the following error message appeared. I was wondering why this did not go through? Im using postgresql in my app.

rake db:migrate
==  ChangeColumnType: migrating ===============================================
-- change_column(:listings, :latitude, :integer)
rake aborted!
An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  column "latitude" cannot be cast to type integer
: ALTER TABLE "listings" ALTER COLUMN "latitude" TYPE integer

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

该表没有DATA。
感谢

NOTE: The table has no DATA. Thanks

推荐答案

我引用手册 ALTER TABLE

I quote the manual about ALTER TABLE:


如果没有隐式或赋值
从旧类型转换为新类型,则必须提供USING子句。

A USING clause must be provided if there is no implicit or assignment cast from old to new type.

您需要的是:


ALTER TABLE listings ALTER longitude TYPE integer USING longitude::int;
ALTER TABLE listings ALTER latitude  TYPE integer USING latitude::int;

或在一个命令中缩短和更快(对于大表格):

Or shorter and faster (for big tables) in one command:

ALTER TABLE listings ALTER longitude TYPE integer USING longitude::int
                    ,ALTER latitude  TYPE integer USING latitude::int;

只要所有条目都可转换为 integer

如果您为列定义了 DEFAULT

This works with or without data as long as all entries are convertible to integer.
If you have defined a DEFAULT for the column, you may have to drop and recreate that for the new type.

这里是有关如何使用ActiveRecord 的博客文章。

或在评论中使用@ mu的建议。他知道他的Ruby。我只是在这里的PostgreSQL很好。

Here is blog article on how to do this with ActiveRecord.
Or go with @mu's advice in the comment. He knows his Ruby. I am only good with the PostgreSQL here.

这篇关于Rails Migrations:试图将字符串的类型从字符串更改为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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