CGI::escape(user.username)
that method will URI-encode the value so it's safe in the URL. Does Rails not do it automatically? Did you try not escaping and putting crazy characters in it?
Edit, and the opposite version:
CGI::unescape(params[:id])
Although I still feel like rails might handle it automatically for you. Might want to test.
Edit again:
Rails does have a .parameterize
method so: user.username.parameterize
will make a string url-friendly, it's documented here: http://apidock.com/rails/v3.0.7/String/parameterize
The main problem with this is that if you have 2 usernames: my.user
and myuser
they will both parameterize to the same string myuser
I think the accepted way of doing it is (as the doc example shows) like this:
"#{user.id}-#{user.username.parameterize}"
this way if you do User.find(params[:id])
it strips out everything after the first number and just uses that as the id. There are gems that will make a unique parameter-friendly string for you to use if you're really that against having the user id in the params (Is there a reason for this concern?). One such gem is friendly_id: https://github.com/norman/friendly_id/ although there are others. The idea is that there's another field on your model specifically for url's, and it's auto-generated on before_create based off of your username field. It has to be unique and parameter friendly, which the gem takes care of.
Hopefully this answer helps you out more :p