0

I want to do like twitter.com does (and so many other sites do) and give my users URLs like:

http://mysite.com/theirusername

Presently, one of my User model validations simply denies blacklisted usernames off of a hardcoded list.

Is there a better way to do this than hardcoding the list? e.g. inspect the routes (code example?)

Any words of wisdom from someone who runs such a site would be valued! I'm sure you must have run into the scenario where you want to use a URL for some new feature, but someone is using it as their username. Has that come up often and what are some ways to handle it? You can always pick another name, use a subdomain, or ask the user to rename I guess. Perhaps it would be worthwhile to blacklist some common english nouns? Any others?

poochenza
  • 485
  • 4
  • 11

1 Answers1

1

Use this:

get ':id', :to => "users#show"

Then you can do things like http://mysite.com/theirusername. Inside the UsersController#show action you will need to use User.find_by_username(params[:id]).

If someone is already using a username that you want to use in the future, send them an email advising them of the change (you should have something to this effect in your Terms and Conditions as well) and give them a period of time to make the change.

You should aim to have some blacklisting feature, which is easy enough to do with a list of words in your User model which is then checked with validates_exclusion_of.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • Hi thanks I actually already have this working sorry if that was unclear. My question is more around validating the usernames directly off the routes (instead of a hardcoded list) and also strategies for preventing and handling collisions with URLs I may wish to add in the future. – poochenza Jan 02 '12 at 22:33
  • Sorry I must be really failing at asking this question. I was trying to ask how to build the blacklist dynamically from the routes, as opposed to maintaining a constant list. I'm actually already using validates_exclusion_of with a static list. Thanks for your help. I asked a hopefully more clear question here http://stackoverflow.com/questions/8706329/rails-validatation-to-ensure-a-username-does-not-clash-with-an-existing-route – poochenza Jan 02 '12 at 23:24
  • 1
    You can't make it dynamically from the routes... easily at least. Check the output of `Rails.application.routes.routes` and go from there. – Ryan Bigg Jan 02 '12 at 23:41