Alex
Alex

Reputation: 36111

Rails case sensitive applications with Postgres

I'm running a new Rails app on Postgresql and I do not understand why on Earth they made Postgreql case sensitive and didn't even make an option to turn this off.

I mean, really, if someone registeres as "Sam" on my site, won't be able to log in as "sam", but there can be two different accounts "Sam" and "sam". This is a disaster, especially taking into consideration the fact that all other major databases are case insensitive.

Now instead of looking for a user like

User.find_by_name(params[:name])

I'll have to do this

User.all(:conditions=>["name ILIKE ?", params[:name]]).first

I can't believe there's no way to avoid this in Rails because it destroys one of the main principles of the framework: database independence.

Is there a better way to implement case insensitive username/e-mail schema?

Upvotes: 3

Views: 1010

Answers (3)

Scott Marlowe
Scott Marlowe

Reputation: 8870

There is a contrib module called citext which creates a case insensitive text type. I think it's only included by default starting in pg 9.0.

Also, you could easily create a unique index to prevent sam, Sam, and SAM from having an account at the same time:

create table abc (users text); create unique index abc_users_ci on abc (upper(users)); insert into abc values ('sam'); insert into abc values ('Sam'); ERROR: duplicate key value violates unique constraint "abc_users_ci"

tada! Or you could just complain that pgsql isn't like mysql.

Upvotes: 3

user330315
user330315

Reputation:

especially taking into consideration the fact that all other major databases are case insensitive

That is simply not true. Oracle, DB2 and Firebird are case-sensitive by default

But I do agree, having such an option would make things a bit easier sometimes.

Upvotes: 1

M. Cypher
M. Cypher

Reputation: 7066

I suppose you could have two DB columns, if preserving the case is important to you:

  • One for the login name, which you will always convert to lower case when the user signs up, and which you use to login the user, after converting the name from the login form to lower case
  • One for the display name, which is what's get displayed as the username and is exactly what the user gave you at signup

Upvotes: 1

Related Questions