myapp.com/@username url in rails routes
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.
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)
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!
精彩评论