I am trying to move to heroku which uses PostgreSQL 8.4 which has a citext column type which is nice since the app was written for MySQL.
Is there any way to use :ci
As others have mentioned, Rails now has native support for the citext
column type (since 4.2).
To migrate existing columns you need to enable the citext extension and then change_column
. Change colum is non-reversible so you'll need separate up
and down
methods.
class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
def up
enable_extension 'citext' # only the first migration you add a citext column
change_column :user, :name, :citext
end
def down
change_column :user, :name, :string
disable_extension 'citext' # reverse order, only the first migration you add a citext column (this will be the last time you remove one in a rollback)
end
end
Disable extension is only required the last time you remove a citext column when rolling back so rather than add ugly comments it might be better to have separate migrations and explain the reason why in your commit message:
# migration 1.rb
class EnableCitext < ActiveRecord::Migration[6.0]
def change
enable_extension 'citext'
end
end
# migration 2.rb
class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
def up
change_column :user, :name, :citext
end
def down
change_column :user, :name, :string
end
end
I'm pretty sure that Rails has only a limited vocabulary of data types. You will likely have to use good old-fashioned SQL to deal with any other types.
Just for the record. Seems like rails 4.2 has native support for this.
Added support for the citext column type in the PostgreSQL adapter.
http://guides.rubyonrails.org/4_2_release_notes.html
Rails 4.2 has native support for the citext
column type.
If you're using Rails < 4.2, you can try using the activerecord-postgresql-citext gem.
This allows you to write migrations like this:
def up
enable_extension("citext")
create_table :models, :force => true do |t|
t.citext :name
t.timestamps
end
end
For anyone wanting to change an existing string
column to citext
, try creating a migration
rails g migration change_username_from_string_to_citext
Then make the migration look like this
class ChangeUsernameFromStringToCitext < ActiveRecord::Migration[6.0]
def change
enable_extension("citext") # Don't forget this line
change_column :users, :username, :citext
end
end