How can I make my rails app display url's as the user name?

In my Rails app a user can create one registry and the url's is for example:

http://localhost:3000/registries/3

How can I make that url be for example:

http://localhost:3000/erinwalker

Thanks in advance.

Answers


The simplest way of doing this is by creating a new route at the bottom of your routes.rb file:

match "/:username" => "registries#show"

It's important to put this at the bottom of your routes.rb file as this will match any route of the format "/whatever" that doesn't match the routes preceding it.

This will point to the show action of your registries controller. So within that action you can just do

@user = User.find_by_username params[:username]
@registry = @user.registry

The friendly_id gem and other slugging gems is, IMO, the easiest approach.

(And here's a friendly_id railscast.)

That said, it's easy to create a route that accepts legal slug values and redirect or look it up yourself.


Need Your Help

jar file gets corrupted while building with maven

java maven-plugin maven-3

while building a war file i am copying a set of jars from a location to a folder inside the war. While the files do get copied , however i think they get corrupted because the same class files of t...

Can NSManagedObject class objects be used as models?

iphone objective-c ios core-data

I have a bit confusion in choosing whether to use NSManagedObjet class objects directly as models or whether to create separate classess for models and create data mappers to map data from these mo...