1

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)

Community
  • 1
  • 1
bergie3000
  • 1,091
  • 1
  • 13
  • 21

2 Answers2

5

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 ])
John Naegle
  • 8,077
  • 3
  • 38
  • 47
  • Thanks. I didn't look closely enough at the error messages I was getting and just (stupidly and lazily) assumed the error was occurring in the routing. Comparing lowercased versions of the username does indeed work. – bergie3000 Dec 03 '12 at 22:18
1

It should work fine to handle this behaviour in the controller, not in the routes.

# config/routes.rb
match ':username' => 'users#show'

# app/controllers/users_controller.rb
def show
  username = params[:username]
  user = User.find_by_username(username) || User.find_by_username(username.downcase) 
  # or something along these lines...
end

An even nicer solution might be to store some kind of slug identification for the user that is always downcased and ready to be used in URLs. You could have a look at the awesome friendly_id gem for that purpose.

Thomas Klemm
  • 10,678
  • 1
  • 51
  • 54