Skip to main content

Rails + MySQL: Case-Sensitive strings in your database

·118 words·1 min· ·
Ruby on Rails
Ariejan de Vroom
Author
Ariejan de Vroom
Jack of all Trades, Professional Software Craftsman

When using Rails + MySQL, you’ll find that normal string (or varchar(255)) fields are case insensitive. This can be quite a nuisance, but it’s easy to resolve. You need to set your table to the utf8_bin collation. By using the binary variant, you’re basically enabling case sensitivity.

create_table :posts, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin' do |t|
  t.string :title, :limit => 100
end

That’s all. The title field is now case sensitive.

Another question I get a lot is how to change the collation and charset for an existing column. That’s easy with the following query. Just make sure to pick the right column and data type:

ALTER TABLE posts MODIFY `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin;

Related

Once and for all: Rails migrations integer :limit option
·99 words·1 min
MySQL Ruby on Rails Rails Sql Migrations Integer Limit
BaseApp: a quick start for your Rails App
·303 words·2 mins
General Ruby Ruby on Rails Rails BaseApp
Useless Ruby Gems for your pleasure
·331 words·2 mins
Blog Ruby on Rails