Hello,
I'm using Rails and I have a User Controller for creating new users. To view current users I have to type something like:
mysite.com/users/USER_ID
I want to change to:
mysite.com/USER_ID
What is the best way to acheive that?
Thanks,
Tam
Hello,
I'm using Rails and I have a User Controller for creating new users. To view current users I have to type something like:
mysite.com/users/USER_ID
I want to change to:
mysite.com/USER_ID
What is the best way to acheive that?
Thanks,
Tam
You would need to define a new root in config/routes.rb like
map.user '/:id', :controller => 'users', :action => 'show'
And then implement the show method - your user id will be in params[:id]
To improve a bit your generated URLs, you could also add a to_param method to the User model to get something like:
def to_param
"#{id}-#{username}"
end
map.users '/:id', :controller => 'users', :action => 'show'
http://yourdomain.com/142-yaraher
That way, Rails will still work properly (by calling .to_i on your param[:id]) and get better URLs.
Keep in mind that you should remove some special characters from the method you would use, so it should be more likely something like:
"#{id}-#{n.downcase.gsub(/[^a-z1-9]+/i, '-')}"