7

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:

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 advance!

1 Answer 1

13

You need to first convert the values M to 1 and F to 0 and then change the column type.

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer. Will doing it this way be performant on large databases - if not, is there a better way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.