views:

35

answers:

2

Hi I have a simple rails question that I am simply unable to figure out. like the title says, I want to get my users controller show page to have the myapp.com/@username url but I don't know how to do this. My knowledge of routes must be fundamentally flawed.

my links now usually look like this:

<%= link_to "#{@user.username}", :controller => "users", :action => "show", :username => @user.username %>

obviously this is not ideal. I'd like them to look like this.

<%= link_to "#{@user.username}", user_path(@user) %>

but I don't know what to do. Nested routes doesn't seem to be the way.

my routes are setup like this:

map.connect '/:username', :controller => 'users', :action => 'show'

but this seemingly just allows me to do what I do now, doesn't let me actually route through there. Any suggestions? PS this is a rails 2.3.8 app.

A: 

In your routes file, you need to setup the resource:

map.resources :users

Now you'll have the nice named routes like user_path(@user) to show the user page, and so on. If you don't want restful routes, you can also just create a single named route:

map.user '/users/:id', :controller => 'users', :action => 'show'

And user_path(@user) will work as well.

By the way, your login example above is incorrect. First, ":login" is being interpreted by the routing engine as a variable, but it's not being used. Also, you wouldn't want the users#show page to be the login page. For starters, show what user? they haven't logged in yet. I hope this helps!

Jaime Bellmyer
yes, I understand how to set up routes. I am trying to set up a specific route, what you have told me to do will give me the url for:
Ryan Max
myapp.com/@username. What you have told me gives you myapp.com/users/@username, which is not what I am looking for.
Ryan Max
Sorry, I didn't understand what you were going for - especially with the ":login" parameter you had previously. The other answer looks like it has it right.
Jaime Bellmyer
my apologies, it was my fault, I was copying and pasting from my app which actually uses "login" as the users username in the DB but I missed that one when I was changing them over to a more readable format. Sorry!
Ryan Max
+3  A: 

your route is correct, however you did not give it a name:

map.USER '/:username', :controller => :users, :action => :show

All caps from me to highlight what you need to change. Now you can call user_path(:username => @user.username)

Faisal