How to remove controller names from rails routes?

后端 未结 4 1470
野的像风
野的像风 2020-12-23 09:31

I would like to trim down the routes on my application so that:

http://myapplication.com/users/peter/questions/how-do-i-create-urls

becomes...

4条回答
  •  被撕碎了的回忆
    2020-12-23 10:20

    Thanks to both @mark and @DanneManne for their help. With their input and a little more tweaking I got it all working. It's not exactly trivial but I'm not sure you could make it much shorter either:


    Final working code

    # setup the basic resources while holding some back for creation below
    resources :users, :except => [:show, :index, :new, :create], :path => '/' do
      resources :questions, :except => [:show]
    end
    
    # for clarity, pick out routes that would otherwise go 
    # to root (such as new_user => '/new')
    resources :users, :only => [:index, :new, :create]
    
    
    # setup questions#show to give clean URLS
    match ':user_id/:question_id', :as => :user_question, 
                                   :via => :get,
                                   :controller => :questions, 
                                   :action => :show
    
    # setup users#show method to give clean URLS
    match ':user_id', :as => :user, 
                      :via => :get, 
                      :controller => :user, 
                      :action => :show
    

    Rake Routes output

        user_questions GET    /:user_id/questions(.:format)          {:action=>"index", :controller=>"questions"}
                       POST   /:user_id/questions(.:format)          {:action=>"create", :controller=>"questions"}
     new_user_question GET    /:user_id/questions/new(.:format)      {:action=>"new", :controller=>"questions"}
    edit_user_question GET    /:user_id/questions/:id/edit(.:format) {:action=>"edit", :controller=>"questions"}
         user_question PUT    /:user_id/questions/:id(.:format)      {:action=>"update", :controller=>"questions"}
                       DELETE /:user_id/questions/:id(.:format)      {:action=>"destroy", :controller=>"questions"}
             edit_user GET    /:id/edit(.:format)                    {:action=>"edit", :controller=>"users"}
                  user PUT    /:id(.:format)                         {:action=>"update", :controller=>"users"}
                       DELETE /:id(.:format)                         {:action=>"destroy", :controller=>"users"}
                 users GET    /users(.:format)                       {:action=>"index", :controller=>"users"}
                       POST   /users(.:format)                       {:action=>"create", :controller=>"users"}
              new_user GET    /users/new(.:format)                   {:action=>"new", :controller=>"users"}
         user_question GET    /:user_id/:question_id(.:format)       {:controller=>"questions", :action=>"show"}
                  user GET    /:user_id(.:format)                    {:controller=>"user", :action=>"show"}
    

提交回复
热议问题