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 :citext with rails (so that if the migrations are run on MySQL the citext would just use string/text?
I found this ticket, but it seems like it isn't going to be a part of rails for a while: https://rails.lighthouseapp.com/projects/8994/tickets/3174-add-support-for-postgresql-citext-column-type
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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With