So I have a gender column on my user model and it's currently a string, I'd like to change it to a integer and make Male '1', and Female '0' as it's presently Male "M" Female "F". When running this migration:
我在我的用户模型上有一个性别栏它是一个字符串,我想把它变成一个整数,让男性为1,而女性为0,因为它现在是男性的“M”女性“F”。当运行这个迁移:
class ChangeGenderToIntegerOnUser < ActiveRecord::Migration
def change
change_column :users, :gender, 'integer USING CAST(gender AS integer)'
end
end
I get the following error:
我得到了以下错误:
error message:
错误信息:
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'
What should I do to properly change gender to integer?
如何正确地将性别转换为整数?
Thanks in advanced!
由于先进的!
1 个解决方案
#1
8
You need to first convert the values M to 1 and F to 0 and then change the column type.
您需要首先将值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
#1
8
You need to first convert the values M to 1 and F to 0 and then change the column type.
您需要首先将值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