devroom.io/content/posts/2009-09-03-rails-mysql-case-sensitive-strings-in-your-database.md

23 lines
963 B
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
date = "2009-09-03"
title = "Rails + MySQL: Case-Sensitive strings in your database"
tags = ["Ruby on Rails"]
slug = "rails-mysql-case-sensitive-strings-in-your-database"
+++
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.
2017-03-20 15:35:19 +00:00
``` ruby
create_table :posts, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin' do |t|
t.string :title, :limit => 100
end
```
2015-03-26 11:28:08 +00:00
That's all. The <code>title</code> 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:
2017-03-20 15:35:19 +00:00
``` sql
ALTER TABLE posts MODIFY `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin;
```
2015-03-26 11:28:08 +00:00