customize rails url with username

前端 未结 4 1313
日久生厌
日久生厌 2020-12-08 12:42

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 navigat

相关标签:
4条回答
  • 2020-12-08 12:53

    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
    
    0 讨论(0)
  • 2020-12-08 12:55

    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
    
    0 讨论(0)
  • 2020-12-08 12:55

    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 讨论(0)
  • 2020-12-08 13:00

    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.

    0 讨论(0)
提交回复
热议问题