2

I am sure there is a simple solution to this but I can't seem to find it.

I want to match the following dynamic username:

 /users/dymanicUsername

How would this look in routes.rb

Thanks for any help.

Allister
  • 851
  • 3
  • 10
  • 21

2 Answers2

5

allister,

To do that, just override to_param in your model. For instance :

#users.rb

def to_param
  self.username
end

You will soon bump into some problems :

  • conflicts with existing routes. For instance, the username should not be 'new', got it ?
  • for fetching you user in the controller, you should create a method (that's what I did, mayybe not the best solution) in your model like this self.find_for_controller(username)
  • your username shall only contains url-enabled characters (forget accents, ponctuations etc...). A solution for this is to have a second attribute names username_urlized, that of course should be unique and not conflicting with other routes

And maybe more problems :)

Also, if you want something like twitter (yoursite.com/dynamicUserName), do the following in routes.rb :

resources :users, :path=>'' do
Marcel Falliere
  • 1,884
  • 21
  • 39
1

Here is a good explanation from 2006 which looks good for Rails 2.3.*: http://garrickvanburen.com/archive/using-names-in-rails-routes-instead-of-ids

The main problems I see is that you would want to ensure not only all of the above that Marcel mentiones, but that the name is unique. ie put an index on name with :unique => true in the migration.

For rails3 to which I'm just now upgrading you would do the routing differently. For example map.connect is replaced by match.