问题
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
回答1:
Rails 4.2+
Rails 4.2 has native support for the citext
column type.
Rails < 4.2
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
回答2:
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
回答3:
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.
回答4:
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
来源:https://stackoverflow.com/questions/2619998/postgresql-rails-citext