Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customize rails url with username

I want to copy the twitter profile page and have a url with a username "http://www.my-app.com/username" and while I can manually type this into the address bar and navigate to the profile page I can't link to the custom URL.

I think the problem is in the routes - here's the code in my routes.rb

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

Also, I have Question and Answer models and I want to link to them with the customized URL like so:

http://www.my-app.com/username/question/answer/2210

like image 486
goddamnyouryan Avatar asked Feb 16 '10 00:02

goddamnyouryan


2 Answers

There's nothing wrong with your route. Just remember to define it at the end, after defining all other routes. I would also recommend using RESTful routes and only if you want to have better looking URLs use named routes. Don't use map.connect. Here's some good reading about Rails routes.

Here's how this could look:

map.resources :questions, :path_prefix => '/:username' do |question|
  question.resources :answers
end

map.resources :users

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

Just a draft you can extend.

like image 83
Paweł Gościcki Avatar answered Oct 21 '22 16:10

Paweł Gościcki


To create urls you need to define to_param method for your user model (read here).

class User < ActiveRecord::Base
  def to_param 
    username
  end
end
like image 45
klew Avatar answered Oct 21 '22 16:10

klew