Use Citext extension for Case InSensitive Columns

Problem πŸ”—

For the columns where we do not care about the capitalization of data inside it, using lower or downcase every where in our application can increase query time.

Solution πŸ”—

The citext extension can provide several benefits for developers who need to work with case-insensitive text data in their database applications.

Where do we use Citext? πŸ”—

  1. Add Migrations - when defining a type for a new column, citext can be given as a type for that column.
  2. Updating Migrations - when updating a type for an already existing column, citext can be given as a type for that column.

This way, lower or downcase can be removed and citext will autmatically compare case-insensitive data.

How do I use Citext? πŸ”—

  1. t.citext :country - when you need to define a column type in a migration.
  2. change_column :users, :email, :citext - when you need to update the column type.

Note: limit cannot be added to citext columns so use model-level validations to control the length of them.

Bad πŸ”—

user = User.find_by(email: "Testerson@gmail.com".downcase)

Good πŸ”—

class EnableCitextExtension < ActiveRecord::Migration[6.1]
  def change
    enable_extension "citext"
  end
end

class ChangeEmailInUsers < ActiveRecord::Migration[6.1]
  def change
    change_column :users, :email, :citext
  end
end

user = User.find_by(email: "Testerson@gmail.com")

Bad πŸ”—

user = User.order("lower(name)")

Good πŸ”—

class ChangeEmailInUsers < ActiveRecord::Migration[6.1]
  def change
    change_column :users, :name, :citext
  end
end

user = User.order("name")

Further Reading πŸ”—