Search code examples
ruby-on-railscase-sensitivecase-insensitive

Case insensitive user names in Rails 3 routes


I am trying to allow users to access their accounts by their user name, regardless of how they capitalize it in the URL. So http://example.com/Username would go to the same page as http://example.com/username.

I am fine with the any other part of the URL being case sensitive (I know that's the standard), but I don't see a need to force a user to get the case of their user name correct in the URL.

Can this be done by adding certain settings in the routes.rb file alone?

I thought this would be straightforward but apparently it isn't.

I found a seemingly simple question here but there's only one answer that I think will help and it's too hacky (by the author's own admission)


Solution

  • I believe this isn't a routing issue and you can address it in your controller code:

    User.where("lower(username) = lower(?)", params[:username]).first!
    

    or

    User.where("lower(username) = ?", params[:username].downcase).first!
    

    or

    User.find(:first, :conditions => [ "lower(username) = ?", params[:username].downcase ])