Rails 3 nested routes question

2019-07-05 11:17发布

问题:

I need some help with routes. Here are my current routes.

resources :users, :only => [:index, :show, :create, :destroy] do
  resources :links, :only => [:create, :destroy], :shallow => true, :on => :member
end

and when I run rake routes I get this

  root               /(.:format)                     {:controller=>"users", :action=>"index"}
  user_links  POST   /users/:user_id/links(.:format) {:action=>"create", :controller=>"links"}
  link        DELETE /links/:id(.:format)            {:action=>"destroy", :controller=>"links"}
  users       GET    /users(.:format)                {:action=>"index", :controller=>"users"}
              POST   /users(.:format)                {:action=>"create", :controller=>"users"}
  user        GET    /users/:id(.:format)            {:action=>"show", :controller=>"users"}
              DELETE /users/:id(.:format)            {:action=>"destroy", :controller=>"users"}

but I am trying to get my routes be this, which is what I had but I can't remember how I got it to work. :(

  root                /(.:format)                     {:controller=>"users", :action=>"index"}
  user_links   POST   /users/:user_id/links(.:format) {:action=>"create", :controller=>"users/links"}
  link         DELETE /links/:id(.:format)            {:action=>"destroy", :controller=>"users/links"}
  users        GET    /users(.:format)                {:action=>"index", :controller=>"users"}
               POST   /users(.:format)                {:action=>"create", :controller=>"users"}
  user         GET    /users/:id(.:format)            {:action=>"show", :controller=>"users"}
               DELETE /users/:id(.:format)            {:action=>"destroy", :controller=>"users"}

What am I doing wrong? What am I missing?

Edit:

I guess the above doesn't really say much. The differences in the routes is this.

  user_links  POST   {:action=>"create", :controller=>"links"} 
  link        DELETE {:action=>"destroy", :controller=>"links"}  


  user_links  POST   {:action=>"create", :controller=>"users/links"}
  link        DELETE {:action=>"destroy", :controller=>"users/links"}

Maybe this will help a bit.

回答1:

try to remove the :shallow => true ... and you should see users/links

see also

http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes



回答2:

Try this first, delete any options in routes.rb

resources :users do
  resources :links, :module => 'users'
end