问题
I want to let users have links to their profiles using their registered usernames.
I store their username exactly how they give it.
I set up my routes to match /:name and then used find_by_name to get it. The problem I have is when you type in example.com/username it doesn't work the name: Username. (Note the uppercase/lowercase difference)
So my question is how can I ignore case in urls?
回答1:
You can store the username
downcased along with a display_name
which is in the format they gave it to you. Then, downcase any input and match it with username
and only use display_name
for, well, display :)
If you wanted, you could even redirect to /DisPlAyName
from /username
after you look up the record.
回答2:
Easiest way is to convert the username in the database and in rails to lower (or upper) case when you are doing the comparison.
User.where('lower(username) = ?', params[:name].downcase).first
Or if you are still using rails 2:
User.find(:first, :conditions => ['lower(username) = ?', params[:name].downcase])
回答3:
One way to do this is to store a lowercase version of their username. When they type in
example.com/UsErNaMe
or example.com/Username
downcase it and match it to the lowercase version in the database.
---OR---
Just make the user have a lowercase username everywhere. (Downcase it when its made)
---OR---
Have a constant type of username. So always have the first letter capitalized or something. Store it as lower case and upcase the first letter everytime you show it.
来源:https://stackoverflow.com/questions/4220865/how-do-i-handle-uppercase-and-lowercase-characters-in-a-custom-url