PG :: InvalidTextRepresentation:ERROR:整数的输入语法无效:“M”

时间:2013-12-21 03:47:54

标签: ruby-on-rails ruby-on-rails-4 psql

所以我在我的用户模型上有一个性别列,它当前是一个字符串,我想把它改成一个整数并使其成为男'1',而女'0'因为它现在是男性“M”女性“ F”。运行此迁移时:

class ChangeGenderToIntegerOnUser < ActiveRecord::Migration
  def change
    change_column :users, :gender, 'integer USING CAST(gender AS integer)'
  end
end

我收到以下错误:

错误消息:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "M"
: ALTER TABLE "users" ALTER COLUMN "gender" TYPE integer USING CAST(gender AS integer)/usr/local/rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `exec'

如何正确地将性别更改为整数?

提前致谢!

1 个答案:

答案 0 :(得分:11)

您需要先将值M转换为1,将F转换为0,然后更改列类型。

class ChangeGenderToIntegerOnUser < ActiveRecord::Migration
  def change
    User.where(gender: 'M').update_all(gender: 1)
    User.where(gender: 'F').update_all(gender: 0)
    change_column :users, :gender, 'integer USING CAST(gender AS integer)'
  end
end