7

Rails + MySQL: Case-Sensitive strings in your database

 3 years ago
source link: https://www.devroom.io/2009/09/03/rails-mysql-case-sensitive-strings-in-your-database/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails + MySQL: Case-Sensitive strings in your database

Posted: 2009-09-03 - Last updated: 2019-06-05

Tagged ruby on rails

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;

My site is free of ads and trackers. I record privacy-respecting usage statistics with Fathom.

Was this post helpful to you? Why not ☕ Buy me a coffee

Copyright © 1999-2020 Ariejan de Vroom <[email protected]>

Live now; make now always the most precious time. Now will never come again.
    – Jean-Luc Picard


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK