Rails Migration to Change string to boolean (PostgreSQL)

When you run the migration to change the the column type from string to boolean, you may encounter this kind of error:

PG::DatatypeMismatch: ERROR:  column "blah" cannot be cast automatically to type boolean
HINT:  You might need to specify "USING blah::boolean".

This just tells you that you need a rule to convert your string to boolean. You can fix with using synthax. For example, if you want all columns to change to false:

change_table :table_name do |t|
  t.change :column_name, :boolean, using: 'false', default: false, null: false
end

Or if you want to convert your existing values from your column, you could do something like this:

change_table :table_name do |t|
  t.change :column_name, :boolean, using: 'cast(column_name as boolean)', default: false, null: false
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.