goddamnyouryan
goddamnyouryan

Reputation: 6896

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

Upvotes: 12

Views: 6525

Answers (4)

Peter
Peter

Reputation: 759

I know this questions is old but it will help someone.

You could try the below. I've used it in a rails 4 project and all seems to be working great. The reason for the as: :admin is I also had a resources posts outside of this scope. It will add a admin to the helper calls e.g. admin_posts_path

scope ":username", module: 'admin', as: :admin do
  get '', to: 'profiles#show'
  resources :posts
end

Upvotes: 1

sonawane
sonawane

Reputation: 1

I have used like this

In View part

portfolio.user.name,:id =>portfolio) %>

and in rout.rb

map.show_portfolio "portfolios/:username", :action => 'show_portfolio', :controller => 'portfolios'

Upvotes: 0

klew
klew

Reputation: 14967

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

Upvotes: 4

Paweł Gościcki
Paweł Gościcki

Reputation: 9594

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.

Upvotes: 13

Related Questions