PostgreSQL + Rails citext

橙三吉。 提交于 2019-12-01 11:16:43
Tyler Rick

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

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

theory

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!