开发者

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


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.


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


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


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'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜